Zend Framework 2 - bjyauthorize - 将新用户与角色联系起来

时间:2013-05-23 07:52:27

标签: php authentication zend-framework2 bjyauthorize

我正在使用bjyauthorize,我对现有用户非常有用。我现在需要动态添加用户。

我可以在表User中手动设置RoleUserRoleLinker之间的连接,但我对新用户的意图如何呢?也许我错过了一些微不足道的事情?

谢谢!

2 个答案:

答案 0 :(得分:5)

用户插入数据库后,ZfcUser User服务会触发register.post事件,因此您只需要侦听该事件。您可以通过将侦听器附加到模块引导程序中的共享事件管理器来实现。

您的侦听器收到的事件实例包含用户服务本身,以及user数据和注册时使用的form,这应该足以建立链接

public function onBootstrap(MvcEvent $e)
{
    $app = $e->getApplication();
    $events = $app->getEventManager();
    $shared = $events->getSharedManager();
    $sm = $app->getServiceManager();

    $shared->attach('ZfcUser\Service\User', 'register.post', function ($e) use ($sm) {
         $userService = $e->getTarget();
         $newUser = $e->getParam('user');
         $registrationForm = $e->getParam('form');
         // do something with the new user info, eg, assign new user role...
    });
}

答案 1 :(得分:0)

以下是完整的解决方案:

public function onBootstrap(MvcEvent $e)
{
    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);

    //You need a copy of the service manager and it has to be set as a member for the lambda function to call it
    $this->sm = $e->getApplication()->getServiceManager();

    $zfcServiceEvents = $e->getApplication()->getServiceManager()->get('zfcuser_user_service')->getEventManager();

    $zfcServiceEvents->attach('register.post', function($e) {

        /** @var \User\Entity\UserPdo $user */
        $user = $e->getParam('user');

        //This is the adapter that both bjyAuthorize and zfcuser use
        $adapter     = $this->sm->get('zfcuser_zend_db_adapter');

        //Build the insert statement
        $sql = new \Zend\Db\Sql\Sql($adapter);

        //bjyAuthorize uses a magic constant for the table name
        $insert = new \Zend\Db\Sql\Insert('user_role_linker');
        $insert->columns(array('user_id', 'role_id'));
        $insert->values(array('user_id' => $user->getId(), 'role_id' => 'user'), $insert::VALUES_MERGE);

        //Execute the insert statement
        $adapter->query($sql->getSqlStringForSqlObject($insert), $adapter::QUERY_MODE_EXECUTE);