使用中间件更改cakephp 3的请求
Change the request of cakephp 3 using middleware
我正在尝试实现一个中间件,该中间件将从 API 读取数据并稍后在控制器上使用它。怎么能做到这一点?
我制作了一个简单的中间件
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()
:
将自定义数据存储在属性中
// ...
// request objects are immutable
$request = $request->withAttribute('dataFromApi', $dataFromApi);
// ...
return next($request, $response);
并通过 ServerRequestInterface::getAttribute()
:
相应地读入你的控制器
$this->set('dataFromApi', $this->request->getAttribute('dataFromApi'));
另见
我正在尝试实现一个中间件,该中间件将从 API 读取数据并稍后在控制器上使用它。怎么能做到这一点? 我制作了一个简单的中间件
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()
:
// ...
// request objects are immutable
$request = $request->withAttribute('dataFromApi', $dataFromApi);
// ...
return next($request, $response);
并通过 ServerRequestInterface::getAttribute()
:
$this->set('dataFromApi', $this->request->getAttribute('dataFromApi'));
另见