3

我阅读了关于 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 时,它就不再起作用了。它将显示以下错误:

致命错误:未捕获的类型错误:传递给 Zend\EventManager\EventManager::attach() 的参数 2 必须是可调用的,给定的对象,在 /var/www/sub.domain.tld/html/module/Application/src/Module 中调用。第 20 行的 php

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

4

1 回答 1

0

我不得不放弃UnauthorizedStrategy上课。onError基本上,我从类的方法中复制了代码UnauthorizedStrategy并进行了修改以满足我的需要。

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();
}
于 2016-12-23T10:30:10.073 回答