Skip to content

Instantly share code, notes, and snippets.

@shinesoftware
Last active August 29, 2015 14:16
Show Gist options
  • Save shinesoftware/2f8e1d523ae33502077c to your computer and use it in GitHub Desktop.
Save shinesoftware/2f8e1d523ae33502077c to your computer and use it in GitHub Desktop.
This is the creation of the UserRegisterListener factory and of its Listener in Zend Framework 2
'factories' => array(
'Base\Listeners\UserRegisterListener' => function($sm){
$config = $sm->get('config');
$config = $config['db'];
$dbAdapter = new Zend\Db\Adapter\Adapter($config);
$regListener = new Base\Listeners\UserRegisterListener();
$regListener->setAdapter($dbAdapter);
return $regListener;
},
<?php
class Module
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$adapter = $e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter');
$sm = $e->getApplication()->getServiceManager();
$eventManager->attach(new UserRegisterListener($adapter)); // <<<< here the registration of the listener!!
?>
<?php
namespace Base\Listeners;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use \BjyProfiler\Db\Adapter\ProfilingAdapter;
class UserRegisterListener implements ListenerAggregateInterface
{
protected $adapter;
/**
* @var \Zend\Stdlib\CallbackHandler[]
*/
protected $listeners = array();
public function __construct(ProfilingAdapter $adapter){
$this->adapter = $adapter;
}
/**
* {@inheritDoc}
*/
public function attach(EventManagerInterface $events)
{
$sharedEvents = $events->getSharedManager();
$this->listeners[] = $sharedEvents->attach('ZfcUser\Service\User', 'register.post', array($this, 'onRegister'), 100);
$this->listeners[] = $sharedEvents->attach('ScnSocialAuth\Authentication\Adapter\HybridAuth', 'registerViaProvider.post', array($this, 'onRegister'), 100);
}
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $index => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$index]);
}
}
}
public function onRegister($e)
{
$user = $e->getParam('user');
if(!empty($user)){
$id = $user->getId();
if(!empty($id) && is_numeric($id)){
$this->adapter->query('INSERT INTO user_role_linker (user_id, role_id) VALUES (' . $id . ', 2)', \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment