且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Symfony中的动态角色

更新时间:2023-11-19 16:04:04

我还没有对此进行测试,但是阅读食谱可能会起作用.

I haven't tested this yet, but reading the cookbook this could work.

此示例是本食谱中示例的修改版本,可满足您的要求.

This example is a modified version of the example in the cookbook to accomodate for your requirements.

class DynamicRoleRequestListener
{
    public function __construct($session, $security)
    {
        $this->session = $session;
        $this->security = $security;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
            // don't do anything if it's not the master request
            return;
        }

        if ($this->session->has('_is_dynamic_role_auth') && $this->session->get('_is_dynamic_role_auth') === true) {
            $role = new Role("ROLE_NEW"); //I'm assuming this implements RoleInterface
            $this->security->getRoles()[] = $role; //You might have to add credentials, too.
            $this->security->getUser()->addRole($role);
        }

        // ...
    }

    private $session;
    private $security;
}

然后将其声明为服务.

services:
    kernel.listener.dynamicrolerequest:
        class: Your\DemoBundle\EventListener\DynamicRoleRequestListener
        arguments: [@session, @security.context]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

类似的问题在这里:如何在使用symfony2(和fosUserBundle)登录后动态添加用户角色?