2012-12-07 78 views
6

我有两个控制器在我的模块,他们都需要看看用户是否登录或不。登录控制器使用DbTable对用户进行身份验证,并将身份写入存储。zend框架2 AuthenticationService

我正在使用> Zend \ Authentication \ AuthenticationService; $ auth = new AuthenticationService();

控制器功能内,但后来我实例化它的实例上的多个pageAction()

为了这个,我写了一个函数到Module.php

如下

public function getServiceConfig() 
    { 
     return array(
      'factories' => array(
       'Application\Config\DbAdapter' => function ($sm) { 
        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
        return $dbAdapter; 
       }, 
       'Admin\Model\PagesTable' => function($sm){ 
        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
        $pagesTable = new PagesTable(new TableGateway('pages',$dbAdapter)); 
        return $pagesTable; 
       }, 
       'Admin\Authentication\Service' => function($sm){ 
        return new AuthenticationService(); 

       } 
      ), 
     ); 
    } 

,你可以看到我每次都返回新的AuthenticationService(),我认为这是不好的。我找不到如何抓取已经实例化的服务实例,或者我不得不为此编写一个单例类。请告知任何示例代码snipets更深入的解释将受到高度重视和赞赏谢谢。

回答

2

试试这个:

public function getServiceConfig() 
{ 
    return array(
     'aliases' => array(
      'Application\Config\DbAdapter' => 'Zend\Db\Adapter\Adapter', 
      'Admin\Authentication\Service' => 'Zend\Authentication\AuthenticationService', 
     ), 
     'factories' => array(
      'Admin\Model\PagesTable' => function ($serviceManager) { 
       $dbAdapter = $serviceManager->get('Application\Config\DbAdapter'); 
       $tableGateway = new TableGateway('pages', $dbAdapter); 
       $pagesTable = new PagesTable($tableGateway); 
       return $pagesTable; 
      }, 
     ), 
    ); 
} 

注意主要的“别名”根阵列的部分,任何其他变化都只是化妆品,你可能更愿意做你建议的原始的方式(如使用工厂检索Zend \ Db \ Adapter \ Adapter实例,而不是别名)。

亲切的问候,

ISE

+0

或者当然,如果你不希望有一个模块特定的服务,您可以只使用$ serviceManager-> GET( 'Zend的\认证\的AuthenticationService') ; – ise

+0

谢谢@ise,这正是我正在寻找。 –