使用中间件更改cakephp 3的请求
我正在尝试实现一个中间件,它将从API读取数据,并稍后在控制器上使用它。你怎么能做到这一点? 我已经做了一个简单的中间件使用中间件更改cakephp 3的请求,cakephp,middleware,cakephp-3.x,Cakephp,Middleware,Cakephp 3.x,我正在尝试实现一个中间件,它将从API读取数据,并稍后在控制器上使用它。你怎么能做到这一点? 我已经做了一个简单的中间件 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) { $dataFromApi = curl_action.... $request->dataFromApi = $dataFromApi; return ne
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$dataFromApi = curl_action....
$request->dataFromApi = $dataFromApi;
return next($request, $response);
}
稍后在控制器上,我希望通过使用
public function display(...$path)
{
$this->set('dataFromApi', $this->request->dataFromAPI);
}
查看\Psr\Http\Message\ServerRequestInterface API,您可以使用ServerRequestInterface::withAttribute将自定义数据存储在属性中:
并通过ServerRequestInterface::getAttribute相应地读入控制器:
另见
// ...
// request objects are immutable
$request = $request->withAttribute('dataFromApi', $dataFromApi);
// ...
return next($request, $response);
$this->set('dataFromApi', $this->request->getAttribute('dataFromApi'));