San Thapa San Thapa - 10 months ago 87
PHP Question

Loading container service on Controller constructor, Symfony

Is there a way to load container service at Controller constructor, like

class PostController extends Controller

protected $breadcrumb;

public function __construct()
//initializing breadcrumb
$breadcrumbs = $this->get("white_october_breadcrumbs");
$breadcrumbs->addRouteItem("Dashboard", "adminPage");
$breadcrumbs->addRouteItem("Post", "postPage");
$this->breadcrumb = $breadcrumbs;


Yes, this is possible via Controller as a Service. However, injecting the Container is considered a bad example. If you want to get the service white_october_breadcrumbs, you can just inject this in your controller service definition; If you use yaml:

    class: app.controller.my_controller
        - "@white_october_breadcrumbs"
public function __construct(Breadcrumbs $breadcrumbs)
    $this->breadcrumbs = $breadcrumbs;

This is a far nicer solution because you don't want your application to depend on the container whenever possible.

Another solution, considering you want this on multiple pages, would be to use event listeners or even custom annotations on actions to add breadcrumbs dynamically. This is not recommended for beginners though.