ZFC Rbac UnauthorizedStrategy 和 Zend Framework 3

ZFC Rbac UnauthorizedStrategy and Zend Framework 3

我看了documentation on Strategies,下面的代码似乎至少在 Zend Framework 2 中是有效的。当然,我测试了它。

public function onBootstrap(EventInterface $e)
{
    $t = $e->getTarget();
    $t->getEventManager()->attach(
        $t->getServiceManager()->get('ZfcRbac\View\Strategy\UnauthorizedStrategy')
    );
}

但是当使用Zend Framework 3 时,它不再有效。它将显示以下错误:

Fatal error: Uncaught TypeError: Argument 2 passed to Zend\EventManager\EventManager::attach() must be callable, object given, called in /var/www/sub.domain.tld/html/module/Application/src/Module.php on line 20

所以基本上我现在被困住了。你能至少指出或指导我正确的方向吗?

我必须放弃 UnauthorizedStrategy class。基本上,我从 UnauthorizedStrategy class 复制了 onError 方法的代码并进行了修改以满足我的需要。

public function onBootstrap(MvcEvent $e)
{
    /** @var EventManager $eventManager */
    $eventManager = $e->getApplication()->getEventManager();

    $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, [$this, 'onError'], 100);
}

public function onError(MvcEvent $event) {
    // Do nothing if no error or if response is not HTTP response
    if (($event->getResult() instanceof HttpResponse)
        || !($event->getResponse() instanceof HttpResponse)
    ) {
        return;
    }

    $baseModel = new ViewModel();
    $baseModel->setTemplate('layout/layout');

    $model = new ViewModel();
    $model->setTemplate('error/403');

    switch ($event->getError()) {
        case GuardInterface::GUARD_UNAUTHORIZED:
            $model->setVariable('error', GuardInterface::GUARD_UNAUTHORIZED);
            break;

        default:
            return; // If it is not unauthorized error, skip it so it will show the more appropriate errors.
    }

    $baseModel->addChild($model);
    $baseModel->setTerminal(true);

    $event->setViewModel($baseModel);

    $response = $event->getResponse() ?: new HttpResponse();
    $response->setStatusCode(403);

    $event->setResponse($response);
    $event->setResult($baseModel);

    $event->stopPropagation();
}