php - Where to put new objects generated by middleware? ← (PHP)

Solution:

Request and Response objects in PSR-7 are implemented as value objects, hence they are immutable.

Every time you need a different object, you create a new instance from the previous one, like

$newRequest = $oldRequest->withMethod('GET');

and from that point on use the new instance.

In middlewares you would have to pass the new instance to the next() function that calls the next middleware (see here for example).

If you need to store in the request object additional data computed from your current request, in the ServerRequestInterface there are defined the withAttribute and the withAttributes methods that allow you to do exactly that.

A common use case for this is for storing the results of routing, but you can surely use them to store other additional data of the request, like session or user data

Answer



Solution:

Do not store at all. Inject it as parameter into consumer function. For instance:

function doSomething(reqest, response, session, user, foo, bar, ...)

Be explicit.

Source