ZF2, using ZFCUser -> using the service manager
zend-framework-modules, zend-framework2
Solution
Have you considered a controller plugin? It would allow those six lines to be condensed down to one call.
Otherwise another more generic approach would be to create a base controller that attached a 'dispatch' event. Matthew Weier O'Phinney wrote a blog post showing this approach http://mwop.net/blog/2012-07-30-the-new-init.html under the "Events" heading.
public function setEventManager(EventManagerInterface $events)
{
parent::setEventManager($events);
$controller = $this;
$events->attach('dispatch', function ($e) use ($controller) {
if (is_callable(array($controller, 'checkIdentity')))
{
call_user_func(array($controller, 'checkIdentity'));
}
}, 100);
}
public function checkIdentity()
{
// Existing ZfcUser code
}
Problem
I setup ZfcUser as an authentication module. The module works great, except for the fact that I have to define it again in every action: ``` $sm = $this->getServiceLocator(); $auth = $sm->get('zfcuser_auth_service'); if ($auth->hasIdentity()) { fb($auth->getIdentity()->getEmail()); } else return $this->redirect()->toRoute('zfcuser'); ``` I tried putting the code in construct, but that didn't work out well. Then I checked around for the Service Manager, but couldn't define it properly with all of the multiple versions that came out. This is the code from my Module class: ``` public function getServiceConfig() { return array( 'factories' => array( 'Todo\Model\TodoTable' => function($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $table = new TodoTable($dbAdapter); return $table; }, ), ); } ``` How do I setup the service correctly?