gpt4 book ai didi

php - 根据用户角色过滤菜单项

转载 作者:搜寻专家 更新时间:2023-10-31 21:05:17 24 4
gpt4 key购买 nike

我的网站上有多个用户角色。一些 Controller 具有基于用户角色的访问限制。
我还有一个菜单(基于 KnpMenuBundle ),我只需要包括登录用户可以访问的项目。

现在我决定以这种方式过滤项目:
1. 向所有 protected 路由添加一个新选项 roles:即 roles: [ROLE_ADMIN, ROLE_MANAGER]
2. 在菜单构建期间将当前用户角色与选项相匹配。

我试图找出 Symfony 中是否有这样的功能(我的意思是在路由设置中定义的角色限制),但我没有找到类似的东西。

所以我的问题是:
1、如何根据用户角色筛选菜单项? (可能已经有相应的功能了吗?)
如果上一个问题的答案是“否”,那么:
2.我怎样才能自己建立这样的过滤?正如我已经提到的,我决定在这种情况下添加一个新选项,那么如何以最佳方式做到这一点?

最佳答案

也许您可以使用我的 KnpMenu Builder 作为示例?

namespace AppBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;

class Builder extends ContainerAware
{
public function mainMenu(FactoryInterface $factory, array $options)
{
$sc = $this->container->get('security.context');

$menu = $factory->createItem('root');
$menu->setChildrenAttribute('class', 'nav navbar-nav');

$menu->addChild('About us', array('route' => 'about'));
$menu->addChild('Contact', array('route' => 'contact'));

/*
* before we use isGranted() we have to check if the security is available, otherwise we will receive an exception on the custom error pages. See also
* http://symfony.com/doc/current/cookbook/controller/error_pages.html#avoiding-exceptions-when-using-security-functions-in-error-templates
*/
if($sc->getToken())
{
$menu->addChild('Members', array('uri' => '#'))
->setAttribute('dropdown', true);

if($sc->isGranted('IS_AUTHENTICATED_REMEMBERED'))
{
$menu['Members']->addChild('My profile', array('route' => 'fos_user_profile_show'));

if($sc->isGranted('ROLE_ADMIN'))
{
$menu['Members']->addChild('Dashboard', array('route' => 'sonata_admin_dashboard'))
->setAttribute('divider_append', true);
}

$menu['Members']->addChild('Logout', array('route' => 'fos_user_security_logout'));
}
else
{
$menu['Members']->addChild('Login', array('route' => 'fos_user_security_login'));
$menu['Members']->addChild('Registration', array('route' => 'fos_user_registration_register'));
}
}

return $menu;
}

}

关于php - 根据用户角色过滤菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33607571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com