Search code examples
phpsymfonysymfony-3.3knpmenubundle

Symfony KnpMenuBundle showing error [MenuBuilder As a Service]


I'm using sumfony 3.3.10, I have installed a fresh project of symfony and I added knpMenuBundle using this command,

composer require knplabs/knp-menu-bundle "^2.0"

Now I followed everything exactly as mentioned here http://symfony.com/doc/master/bundles/KnpMenuBundle/menu_builder_service.html

and added this line {{ knp_menu_render('main') }} in default/index.html.twig file.

Now when I execute the project, its showing me this error,

[InvalidArgumentException]


Menu builder services must be public but "app.menu_builder" is a private service.

config.yml

knp_menu:
        # use "twig: false" to disable the Twig extension and the TwigRenderer
        twig:
            template: KnpMenuBundle::menu.html.twig
        #  if true, enables the helper   for PHP templates
        templating: false
        # the renderer to use, list is also available by default
        default_renderer: twig

MenuBuilder.php

    <?php
namespace AppBundle\Menu;

use Knp\Menu\FactoryInterface;

    class MenuBuilder
{
    private $factory;

    /**
     * @param FactoryInterface $factory
     *
     * Add any other dependency you need
     */
    public function __construct(FactoryInterface $factory)
    {
        $this->factory = $factory;
    }

    public function createMainMenu(array $options)
     {
        $menu = $this->factory->createItem('root');

        $menu->addChild('Home', array('route' => 'homepage'));
        // ... add more children

        return $menu;
     }
 }

services.yml

app.menu_builder:
            class: AppBundle\Menu\MenuBuilder
            arguments: ["@knp_menu.factory"]
            tags:
                - { name: knp_menu.menu_builder, method: createMainMenu, alias: main } # The alias is what is used to retrieve the menu

How can I resolve it. Any help is much appreciated. Thanks


Solution

  • I added public: true to the app.menu_builder service in services.php,

    app.menu_builder:
            class: AppBundle\Menu\MenuBuilder
            public: true
            arguments: ["@knp_menu.factory"]
            tags:
                - { name: knp_menu.menu_builder, method: createMainMenu, alias: main } # The alias is what is used to retrieve the menu
    

    And everything is working fine now.

    Refer : https://symfony.com/doc/current/service_container/alias_private.html#marking-services-as-public-private