为什么 PSR-7 响应的主体是可变的?

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

既然 PSR-7 响应应该是不可变的,为什么我要写这段令人不安的“变异”代码?

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

    return $response;
}

在我看来,虽然 Response 本身是不可变的,这意味着我们在调用 $response->withHeader(…) 时得到一个新对象,但我们仍然可以(而且通常会这样做)改变它的 Body 对象(不是响应中最不重要的部分)。

这不是不一致吗?或者它是完全明智的?这对我来说似乎很奇怪。

您的问题直接在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.