0

我通过在以下位置创建一个类似对象来实现getServiceConfig()Zend AuthenticationServiceAuth Module.php

'AuthService' => function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'tblUSRUsers', 'Email', 'Password', "MD5(?)");

                    $authService = new AuthenticationService();
                    $authService->setAdapter($dbTableAuthAdapter);
                    $authService->setStorage($sm->get('Application\Model\MyAuthStorage'));

                    return $authService;
                },

在控制器动作中,我通过

$this->getServiceLocator()
                    ->get('AuthService');

对于身份验证,我使用获取值

$authservice    = $this->getServiceLocator()->get('AuthService');
$arrUserDetails = $authservice->getIdentity();

它工作正常,这些值可用。

但问题是ServiceLocator在 Controller 构造函数中不可用,因此无法在那里编写上述代码。在每个动作中编写此代码似乎不是一个好习惯。有人可以帮忙吗?

4

2 回答 2

0

可能的解决方案是有一个路由事件处理程序,您可以在其中设置用户凭据:

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager = $e->getApplication()
            ->getEventManager ();

        $eventManager->attach (
            MvcEvent::EVENT_ROUTE,
            function  (MvcEvent $e)
            {
                $auth = $e->getApplication()
                          ->getServiceManager()
                          ->get('AuthService');

                $e->setParam('userinfo', $auth->getUserInfo());
                // update 
                $layout = $e->getViewModel();
                $layout->userinfo = $auth->getUserInfo();           
       });
    }

然后像这样在控制器中访问:

class IndexController extends AbstractActionController
{
    public function indexAction ()
    {
        $this->getEvent()->getParam('userinfo');
于 2013-09-26T10:36:18.330 回答
0

有几种方法可以做到这一点。您可以在 Module 类中重载 ControllerConfig 方法,以便您可以根据需要实例化控制器。或者您可以编写一个控制器插件来处理身份验证并返回身份。

编辑

应该早点提供这些链接,但没有太多的电话访问权限;)。

要了解 ControllerConfig,请查看此博客文章。Module 类中 getControllerConfig 方法的一半有一个解释。这是模块管理器在实例化模块类时寻找的一种方法,它允许您自定义该模块中控制器的实例化。一旦您返回 Controller 类,Controller Manager 就会注入其余的 Controller 依赖项(插件等)。

控制器插件是注入到每个控制器中的小类,并且可以从动作中调用以执行一些常见的代码。当您$this->getServiceLocator()在控制器操作中使用时,您使用的是插件。

于 2013-09-26T10:24:15.497 回答