Zend framework2 ZF2,使用ZFCUser->;使用服务管理器

Zend framework2 ZF2,使用ZFCUser->;使用服务管理器,zend-framework2,zend-framework-modules,Zend Framework2,Zend Framework Modules,我将ZfcUser设置为身份验证模块。该模块工作得很好,除了我必须在每个动作中重新定义它: $sm = $this->getServiceLocator(); $auth = $sm->get('zfcuser_auth_service'); if ($auth->hasIdentity()) { fb($auth->getIdentity()->getEmail()); } else return $this->redirect()->toRo

我将ZfcUser设置为身份验证模块。该模块工作得很好,除了我必须在每个动作中重新定义它:

$sm = $this->getServiceLocator();
$auth = $sm->get('zfcuser_auth_service');
if ($auth->hasIdentity()) {
    fb($auth->getIdentity()->getEmail());
}
else return $this->redirect()->toRoute('zfcuser');
我尝试将代码放入构造中,但效果不好。 然后我检查了一下服务管理器,但无法用所有的多个版本正确地定义它

这是我的模块类中的代码:

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

如何正确设置服务?

您考虑过控制器插件吗?这将使这六条电话线浓缩成一个电话

否则,另一种更通用的方法是创建附加“分派”事件的基本控制器。Matthew Weier O'Phinney在“事件”标题下写了一篇博客文章,展示了这种方法

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
}