San Thapa San Thapa - 6 months ago 54
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

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:

service:
    class: app.controller.my_controller
    arguments:
        - "@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.