在 Symfony3 中,对我来说最好和最简单的解决方案是在 MenuBuilder.php 中:
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class MenuBuilder implements ContainerAwareInterface
{
use ContainerAwareTrait;
public function __construct(FactoryInterface $factory, AuthorizationCheckerInterface $authorizationChecker)
{
$this->factory = $factory;
$this->checker = $authorizationChecker;
}
public function mainMenu(array $options)
{
$menu = $this->factory->createItem('root');
$menu->addChild('Home', array('route' => 'homepage'));
$menu->addChild('Blog', array('route' => 'blog_homepage'));
$menu['Blog']->addChild('About', array('route' => 'blog_about'));
$menu['Blog']->addChild('Contact Us', array('route' => 'blog_contact'));
if($this->checker->isGranted('ROLE_ADMIN')) {
$menu->addChild('Admin', array('route' => 'sonata_admin_dashboard'));
}
$menu->addChild('User', array('route' => 'fos_user_profile_show'));
$menu['User']->addChild('Register', array('route' => 'fos_user_registration_register'));
$menu['User']->addChild('Change password', array('route' => 'fos_user_change_password'));
$menu['User']->addChild('Log Out', array('route' => 'fos_user_security_logout'));
// ... add more children
return $menu;
}
}
Donf 忘记将“@security.authorization_checker”添加到服务中的参数