PSR-7 getParsedBody()

499 views
Skip to first unread message

Jason Judge

unread,
Jan 24, 2016, 5:41:49 AM1/24/16
to PHP Framework Interoperability Group
Hopefully just a quick question.

The `Psr\Http\Message\ServerRequestInterface` interface has a `getParsedBody()` method to deserialize the body content when a request is made to the application.

The `Psr\Http\Message\ResponseInterface` (extending `MessageInterface`) does not have a `getParsedBody()` method to deserialize the body content *returned* to the application as a request response.

I was wondering, what is the reasoning behind this? Why does PSR-7 advocate parsing the body for initial requests *to* the server, but not for responses to requests *from* the server?

I realise that $_POST will only be relevant for the ServerRequestInterface instance, but for any content type other than application/x-www-form-urlencoded and multipart/form-data, the situation will be the same. Is it because `getParsedBody()` only MAY parse the data, i.e. it does not have to, so cannot be relied upon?

Matthew Weier O'Phinney

unread,
Jan 24, 2016, 9:23:56 AM1/24/16
to php...@googlegroups.com

First, a clarification: the assumption with ServerRequestInterface is not that it will parse the data; rather, it's that a process along the way will parse it and create and return a new request with the parsed results. getParsedBody() exists because in a typical request, you may want to do this once, but access it multiple times; without it, your code needs to parse each time it needs body values, and is coupled to the logic for parsing. This is true of the other methods that correspond to superglobals as well.

For client-side responses, the story is different: you typically parse exactly once, and then consume only the values returned. As such modern client libraries like guzzle provide toolchains for doing this kind of work, often using map/reduce-style functionality that returns something at the end — and API wrapper libraries are using such results in fluent, DSL-like classes.

In other words, the parsed body values are one of many sources of input for a server-side request, but they are the primary result of a client-side response. As such, different treatments.

Jason Judge

unread,
Jan 25, 2016, 7:47:07 AM1/25/16
to PHP Framework Interoperability Group

I see, so it's about how many "eyes" are looking at the data. With a ServerRequestInterface many layers in a framework may need to look at the data before deciding what to do with it. But with a ResponseInterface the message comes back to one place that knows the data is meant for it only.

It's like a letter arriving at an office, that needs to go through sorting and distribution before it gets to the intended recipient, vs an office worker making a phone call and getting a question answered in that conversation without anyone else being involved.

So getParsedBody() is a convenient cache of processed data.
Reply all
Reply to author
Forward
0 new messages