sampart / BreadcrumbsBundle

A small breadcrumbs bundle for Symfony
Other
188 stars 68 forks source link

Service "white_october_breadcrumbs" not found #99

Closed gazouweb closed 5 years ago

gazouweb commented 5 years ago

Hi,

With Symfony 4, when I want to use the service "white_october_breadcrumbs" in my controller with the code:

$breadcrumbs = $this->get("white_october_breadcrumbs");

I have the following error:

Service "white_october_breadcrumbs" not found: even though it exists in the app's container, the container inside "App\Controller\MenuController" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session", "templating" and "twig" services.Try using dependency injection instead.

Can you help me ?

gazouweb commented 5 years ago

I found a solution :

I had this function in my controller :

public` static function getSubscribedServices()
    {
        $services = parent::getSubscribedServices();
        return array_merge($services, array(
            'white_october_breadcrumbs' => '?'.Breadcrumbs::class
        ));
    }

and I use this line elsewhere in my controller :

$breadcrumbs = $this->get("white_october_breadcrumbs");
sampart commented 5 years ago

Thanks for sharing your solution, @gazouweb. Sorry for the delay in replying.

Another approach here is to use dependency injection - if you add a type-hinted parameter for breadcrumbs in your controller method, Symfony will inject the right thing automatically for you:

use WhiteOctober\BreadcrumbsBundle\Model\Breadcrumbs;

class YourController extends AbstractController
{
    public function yourAction(Breadcrumbs $breadcrumbs)
    {
        // ...
    }
}

I've updated the docs to show this; thanks for flagging!