This bundle gives you a really convenient way to create menus by following
a convention and - if needed - injecting the entire container.

However, if you want to, you can instead choose to create a service for your
menu object. The advantage of this method is that you can inject the exact
dependencies that your menu needs, instead of injecting the entire service
container. This can lead to code that is more testable and also potentially
more reusable. The disadvantage is that it needs just a little more setup.

Start by creating a builder for your menu. You can stick as many menus into
a builder as you want, so you may only have one (or just a few) of these
builder classes in your application:

Next, register two services: one for your menu builder, and one for the menu
object created by the createMainMenu method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

# app/config/services.ymlservices:app.menu_builder:class:AppBundle\Menu\MenuBuilderarguments:["@knp_menu.factory"]app.main_menu:class:Knp\Menu\MenuItem# the service definition requires setting the classfactory:["@app.menu_builder",createMainMenu]arguments:["@request_stack"]tags:-{ name:knp_menu.menu, alias:main}# The alias is what is used to retrieve the menu# ...

Note

The menu service must be public as it will be retrieved at runtime to keep
it lazy-loaded.