在Module.php中,我实现了代码,以便在允许访问受限页面之前检查用户的身份验证。
这是我的Module.php
<?php
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
class Module
{
protected $whitelist = array('authenticate', 'home');
public function onBootstrap(MvcEvent $event)
{
$application = $event->getApplication();
$eventManager = $application->getEventManager();
$serviceManager = $application->getServiceManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$authService = $serviceManager->get('Zend\Authentication\AuthenticationService');
$whitelist = $this->whitelist;
$eventManager->attach(MvcEvent::EVENT_ROUTE, function ($e) use ($whitelist, $authService) {
$routeMatch = $e->getRouteMatch();
//No route match, this is a 404
if (!$routeMatch instanceof RouteMatch) {
return;
}
//Route is whitelisted
$matchedRouteName = $routeMatch->getMatchedRouteName();
if (in_array($matchedRouteName, $whitelist)) {
return;
}
//User is authenticated
if ($authService->hasIdentity()) {
return;
}
//Redirect users
$router = $e->getRouter();
$url = $router->assemble(array(), array(
'name' => 'authenticate'
));
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
return $response;
}, -100);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'Zend\Authentication\AuthenticationService' => function ($serviceManager) {
return $serviceManager->get('doctrine.authenticationservice.orm_default');
}
)
);
}
}
这在浏览器中完美运行,但在运行单元测试时会抛出以下错误。
Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.authenticationservice.orm_default
问题是onBoostrap中的服务管理器无法初始化身份验证适配器,这是带问题的代码
$authService = $serviceManager->get('Zend\Authentication\AuthenticationService');
当我禁用$ authService所有单元测试成功运行时,我无法找出导致此问题的确切问题,这可能是什么问题?
感谢。
答案 0 :(得分:1)
因为当您运行测试时,您必须配置实体管理器。
使用auth模块,您有一个doctrine实体管理器,在您的引导测试中尚未配置。是吗 ?
默认情况下,您应该拥有doctrine.entitymanager.orm_default
但不是您在错误中拥有此doctrine.authenticationservice.orm_default
我猜你必须在测试中添加一个实体管理器。