Why is a PSR-7 Response’s Body mutable?

838 views Asked by At

Since a PSR-7 Response is supposed to be immutable, why can I write this disturbingly "mutating" piece of code?

public function controller(Response $response): Response
{
    $response->getBody()->write("Hey.");

    return $response;
}

It seems to me that while the Response in itself is immutable, meaning that we get a new object when we call $response->withHeader(…) for instance, we still can (and usually do) mutate its Body object (not the least important part of the response).

Isn’t that inconsistent? Or is it perfectly sensible? It just seems quite weird to me.

1

There are 1 answers

9
Chris Haas On BEST ANSWER

Your question is directly answered in the meta for PSR-7:

Why are streams mutable?
The StreamInterface API includes methods such as write() which can change the message content – which directly contradicts having immutable messages.

The problem that arises is due to the fact that the interface is intended to wrap a PHP stream or similar. A write operation therefore will proxy to writing to the stream. Even if we made StreamInterface immutable, once the stream has been updated, any instance that wraps that stream will also be updated – making immutability impossible to enforce.

Our recommendation is that implementations use read-only streams for server-side requests and client-side responses.