Al *_* ѫ 5 php zend-framework2 zend-framework3 zf3
我有一个带ACL的新ZF3应用程序.现在,在未经授权的情况下,我需要重定向到错误页面(例如403).我认为最好的方法是发射一个事件然后抓住它,但我失败了......
所有都在我的用户模块中,在Module.php(摘录)中:
namespace User;
use Zend\Mvc\MvcEvent;
use Zend\Permissions\Acl\Acl;
use Zend\Stdlib\Response ;
use Zend\View\Model\ViewModel;
[...]
class Module implements ConfigProviderInterface
{
[...]
public function onBootstrap(MvcEvent $e)
{
// Set event to check ACL, then to handle unauthorized access
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'checkProtectedRoutes'), 1);
$eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'dispatchError'), -999);
// Init ACL
$this->initAcl($e);
}
public function initAcl(MvcEvent $e)
{
[...]
}
public function checkProtectedRoutes(MvcEvent $e)
{
// My access logic working fine. return if OK
[...]
// if authorization failed
$e->setError('ACL_ACCESS_DENIED') ;
$e->setParam('route', $route);
$e->getTarget()->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $e);
}
public function dispatchError(MvcEvent $e)
{
// Check error type
$error = $e->getError();
switch ($error) {
case 'ACL_ACCESS_DENIED' :
// What should I do here ?
break;
default:
return ;
break;
}
return false ;
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我的事件被触发时,我的dispatchError()方法永远不会调用,并且ZF3会哭:
可捕获的致命错误:传递给Zend\Mvc\View\Http\RouteNotFoundStrategy :: detectNotFoundError()的参数1必须是Zend\Mvc\MvcEvent的实例,Zend\EventManager\Event的实例,在/ xxxxxxx/vendor/zendframework中调用第271行的/zend-eventmanager/src/EventManager.php,第135行的/xxxxxxxx/vendor/zendframework/zend-mvc/src/View/Http/RouteNotFoundStrategy.php中定义
哪里我错了,我应该如何触发/捕捉此事件?
由于您使用的是 ZF3,我可能建议将您的 ACL 逻辑从引导程序移至中间件中。如果 ACL 表明请求可以,您将调用 $next,它最终会到达控制器。如果不是,请将响应的状态设置为 403 并返回响应。查看 zend-mvc 上的扩展坞,因为他们有一个针对这个问题的食谱示例。
https://docs.zendframework.com/zend-mvc/cookbook/middleware-in-listeners/