【发布时间】:2014-08-10 13:03:25
【问题描述】:
在 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 所有单元测试成功运行时,我无法找出导致此问题的确切问题,这可能是什么问题?
谢谢。
【问题讨论】:
标签: unit-testing doctrine-orm zend-framework2 phpunit