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

3

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

我该如何正确设置这项服务?

1个回答

5
您考虑过使用控制器插件吗?这将使这六行代码压缩成一行调用。
否则,另一个更通用的方法是创建一个基本控制器,附加一个“分配”事件。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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接