我将 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;
},
),
);
}
如何正确设置服务?
最佳答案
您是否考虑过 Controller 插件?它可以将这六行代码压缩为一个调用。
否则,另一种更通用的方法是创建一个附加"dispatch"事件的基本 Controller 。 Matthew Weier O'Phinney 写了一篇博文展示这种方法 http://mwop.net/blog/2012-07-30-the-new-init.html在“事件”标题下。
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
}
关于zend-framework2 - ZF2,使用 ZFCUser -> 使用服务管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12100201/