我是这样做的.
我已将KnpMenu注册为服务并将entityManager传递给该类.
stex_site_main.menu_builder:
class: Stex\SiteBundle\Menu\MenuBuilder
arguments: ["@knp_menu.factory", "@doctrine.orm.entity_manager"]
stex_site_main.menu.main:
class: Knp\Menu\MenuItem
factory_service: stex_site_main.menu_builder
factory_method: createMainMenu
arguments: ["@request"]
scope: request
tags:
- { name: knp_menu.menu, alias: main }
有了EM,我打开一个Entity MyMenu并生成在db中编写的菜单项.
private $factory;
private $em;
public function __construct(FactoryInterface $factory, \Doctrine\ORM\EntityManager $em)
{
$this->factory = $factory;
$this->em = $em;
}
public function createMainMenu(\Symfony\Component\HttpFoundation\Request $request)
{
$menu = $this->factory->createItem('root');
$menu->setChildrenAttribute('class', 'menu');
$menu->addChild(' ', array('route' => 'stex_site_home_home', 'attributes' => array('class' => 'home')));
$menu->setCurrentUri($request->getRequestUri());
$em = $this->em;
$q = $em->createQuery('
SELECT m
FROM StexAdminBundle:MyMenu m
WHERE m.status=1
ORDER BY menu.position');
$r = $q->getResult();
foreach($r as $menu) {
$menu->addChild($menu->getName(), array('route' => $menu->getRoute(), 'routeParameters' => array(json_decode($menu->getParams())));
}
return $menu;
}
将控制器映射到菜单条目(和子子子等)在现实世界的应用程序中是非常罕见的情况(根据我的说法)并且不会非常有用(认为你必须编写主要是“例外”的控制器不包括,等等).
拥有DB菜单是我的解决方案.非常灵活,用户可以使用漂亮的界面等进行编辑.