【发布时间】:2017-01-07 21:23:09
【问题描述】:
我正在尝试使我的 ZF2 User 模块适应 ZF3 MVC。它有一个身份验证服务管理器,在 Module 类内的 onBootsrap 函数中调用每个请求(即页面加载)来检查用户是否经过身份验证。
由于serviceLocator 和ServiceAware 不再可用,我正在尝试创建AuthenticationServiceFactory,但我还没有成功。您对我做错了什么以及如何使用 ZF3 做错有任何想法吗?
这是我的module/User/config.module.config.php 文件的简化版本
namespace User;
use ...
return [
'router' => [...],
'controllers' => [...],
'service_manager' => [
'factories' => [
Service\AuthenticationServiceFactory::class => InvokableFactory::class,
],
],
];
这是我的module/User/src/Service/AuthenticationServiceFactory.php 文件
namespace User\Service;
use Interop\Container\ContainerInterface;
use Zend\Authentication\AuthenticationService;
use Zend\ServiceManager\Factory\FactoryInterface;
use Zend\Db\Adapter\Adapter as DbAdapter;
use Zend\Authentication\Adapter\DbTable\CredentialTreatmentAdapter as AuthAdapter;
use Zend\Authentication\Storage\Session as Storage;
class AuthenticationServiceFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$controllerPluginManager = $container;
$serviceManager = $controllerPluginManager->get('ServiceManager');
$config = $serviceManager->get('configuration');
$dbAdapter = new DbAdapter($config['db']); // Mysqli driver working in other modules
$authAdapter = new AuthAdapter($dbAdapter);
$authAdapter->setTableName('user')->setIdentityColumn('username')->setCredentialColumn('password');
$storage = new Storage();
return new AuthenticationService($storage, $authAdapter);
}
}
这是我的module/User/src/Module.php 文件
namespace User\Service;
use Zend\Mvc\MvcEvent;
use Zend\Authentication\Adapter\DbTable\CredentialTreatmentAdapter;
class Module
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function onBootstrap(MvcEvent $e)
{
$services = $e->getApplication()->getServiceManager();
$auth = $services->get(AuthenticationServiceFactory::class);
// Returns Fatal error: Call to undefined method Zend\Authentication\AuthenticationServiceFactory::setIdentity()
// $auth is an AuthenticationServiceFactory object and not the AuthenticationService returned by its __invoke() function
$this->authAdapter->setIdentity('dummy_user_name');
$this->authAdapter->setCredential('dummy_password');
print_r($this->authAdapter->authenticate());
}
}
有什么想法吗?
【问题讨论】:
-
我在这里写了一个 ACL/Auth 模块,它可以帮助您了解有关侦听器和事件策略的想法github.com/Saeven/zf3-circlical-user
标签: zend-framework zend-auth zend-framework3 zf3