San Thapa San Thapa - 1 year ago 104
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;

Answer Source

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.