Php zend framework 2身份验证服务
我的模块中有两个控制器,它们都需要查看用户是否登录。登录控制器使用DbTable对用户进行身份验证,并将标识写入存储器 我正在使用>Zend\Authentication\AuthenticationService$auth=newauthenticationservice() 在控制器函数中,但我在多个pageAction()上实例化了它的实例 为此,我在Module.php中编写了一个函数 如下Php zend framework 2身份验证服务,php,authentication,zend-framework2,Php,Authentication,Zend Framework2,我的模块中有两个控制器,它们都需要查看用户是否登录。登录控制器使用DbTable对用户进行身份验证,并将标识写入存储器 我正在使用>Zend\Authentication\AuthenticationService$auth=newauthenticationservice() 在控制器函数中,但我在多个pageAction()上实例化了它的实例 为此,我在Module.php中编写了一个函数 如下 public function getServiceConfig() {
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(),我认为这是不好的。我找不到如何获取已实例化的服务实例或
我必须为此编写一个单例类。请告知任何有更深入解释的示例代码,我们将予以高度重视和感谢 试试这个:
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当然,如果您不想使用特定于模块的服务,您可以使用$serviceManager->get('Zend\Authentication\AuthenticationService');