扩展RestController时,ZF-Rest $ event-> getRouteMatch()为null

时间:2016-09-06 11:14:54

标签: php rest zend-framework2

我正在项目中使用zf-rest作曲家包。

这是我资源文件中的create方法。

public function create($data)
{
    var_dump($e->getRouteMatch()->getParams()); 
    // all URL params are listed here with the correct values
    die();
}

我现在已将RestController扩展为CustomRestController并添加了

'controller_class' => CustomRestController::class

到配置文件。

现在,var_dump($event->getRouteMatch());在资源类中是null

public function onBootstrap(MvcEvent $e)中,使用

$eventManager->attach(
    MvcEvent::EVENT_ROUTE, 
    function($e) {
        // I can still read `$e->getRouteMatch()->getParams()`
    } 
);

非常感谢任何有关如何处理此问题的建议。

1 个答案:

答案 0 :(得分:0)

更新回答

根问题是09-06 16:58:50.958 7229-7283/kz.halykbank.halykewallet D/OkHttp: --> POST https://www.hbapimanager.azure-api.net/Wallet/CheckNumber http/1.1 09-06 16:58:50.959 7229-7283/kz.halykbank.halykewallet D/OkHttp: Content- Type: application/json 09-06 16:58:50.959 7229-7283/kz.halykbank.halykewallet D/OkHttp: Content-Length: 27 09-06 16:58:50.959 7229-7283/kz.halykbank.halykewallet D/OkHttp: Ocp-Apim-Subscription-Key: xxxxxxxxxxxxxxxxxxxxxxxxx 09-06 16:58:50.959 7229-7283/kz.halykbank.halykewallet D/OkHttp: {"phone":"x(xxx)xxx-xx-xx"} 09-06 16:58:50.959 7229-7283/kz.halykbank.halykewallet D/OkHttp: --> END POST (27-byte body) 09-06 16:58:51.666 7229-7283/kz.halykbank.halykewallet D/OkHttp: <-- HTTP FAILED: java.net.UnknownHostException: Unable to resolve host "www.hbapimanager.azure-api.net": No address associated with hostname 。它使用FQCN,如:

RestParametersListener

因此,扩展RestController会导致这些$listener = $events->attach( RestController::class, // more params ); / attach调用以避免使用新控制器。

一个干净的解决方法是将detach扩展到RestParametersListener并更改其中的控制器类。

在扩展之后,我还在CustomRestParametersListener中添加了它:

module.config.php

初步回答

找到解决方法,直到问题102和103得到zf-rest开发团队的修复

在我的'service_manager' => [ 'invokables' => [ 'ZF\Rest\RestParametersListener' => CustomRestParametersListener::class, ], // ... ]

CustomRestController

其中:

try {
    $this->manuallyInjectRouteMatch(); // added this line
    $value = $this->getResource()->create($data);
} catch (Throwable $e) {
    return $this->createApiProblemFromThrowable($e);
} catch (Exception $e) {
    return $this->createApiProblemFromException($e);
}

此外,还需要为其他REST方法调用/** * By using this factory instead of the default one and by creating a CastorRestController * instead of RestController, the routeMatch property is "lost". * Manually injecting it so we have access to it inside the *Resource class */ private function manuallyInjectRouteMatch() { $r = new \ReflectionProperty(Resource::class, 'routeMatch'); $r->setAccessible(true); $r->setValue($this->getResource(), $this->getEvent()->getRouteMatch()); }