I’m using some middlewares, and I would like to pass arguments on the backleg.
Meaning: I would like the equivalent of $request->setAttribute(), e.g. $response->setAttribute() . However, such a function does not exist.
How can I send information to my outer middlewares? The only thing that is returned is the $response, and I don’t see anything that would allow this. I guess I could “hijack” the header/body to set these attributes, then unset them in the outbound middleware, but that seems hardly ideal.
Any ideas for a better solution?
Yes, you can do this with the Request object as it follows PSR-7. You are passing both the
Response along to the next callable. In your middleware, you would do
public function __invoke(Request $request, Response $response, $next)
$request = $request->withAttribute('foo', 'bar');
$response = $next($request, $response);
Then later in your app (or in later middleware) you can retrieve it from
$foo = $request->getAttribute('foo'); // bar
I failed at making sense in my OP, I see
I can’t use $request, because I’m on my way out of the route already.
MW1 -> MW2 -> MW3 -> route (here I want to set an attribute) -> MW3 -> MW2 -> MW1 (here I want to get the attribute and do stuff with it) -> response (which should then not have the attribute anymore, neither in header nor body)
As the middlewares only ever return the $response via $next, the $request is not updated on the way back out of the route.
Yes, I misunderstood, sorry.
Upon further research, it seems this is an issue with PSR-7 itself. Just googling for “PSR7 attribute on response” yields a lot of discussion threads about this particular issue (and a number of related issues). Didn’t find a clear suggestion on how to work around it, except to (mis)use the $response->withHeader() , so I’ll stick with that for now, but I’m very interested in better ideas .