phpauthenticationzend-framework2bjyauthorize

Zend Framework 2 - bjyauthorize - Link new user with role


I'm using bjyauthorize and I works great for existing users. I now are in need to add users dynamically.

I can set the connection between User and Role manually in the table UserRoleLinker but how do I it the way it is meant to be for new users? Maybe I missed something trivial?


Solution

  • The ZfcUser User service triggers a register.post event after the user is inserted in the db, so you just need to listen to that event. You can do that by attaching a listener to the shared events manager in your module bootstrap.

    The event instance received by your listener contains the user service itself, plus the user data, and the form that was used during registration, which should be enough to make the link

    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...
        });
    }