Search code examples
cakephpmiddlewarecakephp-3.x

Change the request of cakephp 3 using middleware


I am trying to implement a middleware who will read data from an API and will use it later on the controller. How can do this ? I have made a simple middleware where i have

public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
    $dataFromApi = curl_action....
    $request->dataFromApi = $dataFromApi;
    return next($request, $response);
}

Later on the controller i want to have access to these data by using

public function display(...$path)
{
    $this->set('dataFromApi', $this->request->dataFromAPI);
}

Solution

  • Look at the \Psr\Http\Message\ServerRequestInterface API, you can store your custom data in an attribute using ServerRequestInterface::withAttribute():

    // ...
    // request objects are immutable
    $request = $request->withAttribute('dataFromApi', $dataFromApi);
    // ...
    return next($request, $response);
    

    and read in your controller accordingly via ServerRequestInterface::getAttribute():

    $this->set('dataFromApi', $this->request->getAttribute('dataFromApi'));
    

    See also