Last active
December 30, 2015 18:49
-
-
Save magickatt/7870244 to your computer and use it in GitHub Desktop.
Add user roles on register with ZfcUser in Zend Framework 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Module | |
{ | |
public function onBootstrap(MvcEvent $e) | |
{ | |
/* | |
* Other module code as usual... | |
*/ | |
/* | |
* If a user registers, we need to assign them the default 'user' | |
* role (and the 'guest' role) | |
*/ | |
$zfcServiceEvents = $e->getApplication() | |
->getServiceManager() | |
->get('zfcuser_user_service') | |
->getEventManager(); | |
$zfcServiceEvents->attach('register.post', function($e) use($e) { | |
$class = 'Application\Entity\User'; | |
$em = $e->getApplication() | |
->getServiceManager() | |
->get('doctrine.entitymanager.orm_default'); | |
/* | |
* Get the last inserted user ID | |
* | |
* This is implemented this way as a) the user is not actually | |
* passed back in the event payload, b) I assume that this is | |
* counted as a separate transaction because the user is saved | |
* in the 'register' event, therefore LAST_INSERT_ID() returns nothing | |
* | |
* @todo Fork ZfcUser and fix the bug whereby the user is not sent in | |
* the event payload (which means we could add user roles to it directory) | |
*/ | |
$q = $em->createQuery("SELECT MAX(u.id) FROM " . $class . " u"); | |
$resultset = $q->getResult(); | |
$userId = (integer) array_pop(array_pop($resultset)); | |
// Retrieve the user that was just inserted | |
$user = $em->getRepository($class)->find($userId); | |
// If the event contained the user (as it looks like it should) you could do this instead | |
/*$user = $e->getParam('user');*/ | |
// Add on the user roles that you want them to have | |
$defaultUserRole = $em->getRepository('Application\Entity\Role') | |
->findOneByRoleId('guest'); | |
$standardUserRole = $em->getRepository('Application\Entity\Role') | |
->findOneByRoleId('user'); | |
$user->addRole($defaultUserRole); | |
$user->addRole($standardUserRole); | |
// Save the user | |
$em->persist($user); | |
$em->flush(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment