PSR-7 Standard – Part 3 – Response

PSR-7 Standard – Part 3 – Response

This post is part of series:

In the last blog post we described the RequestInterface of PSR-7. Every application will process this request and returns a response to the calling client. The response is the part where a backend sends a result of an server operation back to the client. Let’s view how the ResponseInterface is designed.

Like the request, the response has to be build in an immutable way. This means that every method returns a new instance of the object instead of a reference to the existing object. The interface is a lot simpler than the RequestInterface. It contains only one method withStatus to pass a HTTP status code. All the other methods are inherited by MessageInterface which we already know from RequestInterface. This is consequent, because the Request and Response are communicating trough messages. So the Request sends a message and the Response returns a message.

Using Guzzle

Like in the previous article we make use of the PSR7 library of the Guzzle project.

The installation is easy as:

composer.phar require guzzlehttp/guzzle:~6.0

We replace the “server.php” of the previous article with this code:

The script is the equivalent of the server.php script of previous article where we simply dumped the $_SERVER array. Not it is HTTP compliant.

We build a new response with a status code 200 and “OK” as phrase for the HTTP status header line. According to the RequestInterface we must pass a stream as parameter. To simply convert a string we can use the stream_for function of the Guzzle library.

At the end we need to create a valid HTTP message string which can simply pushed to the client which PHP’s echo function. Guzzle provides the handy str function to convert an instance of MessageInterface to a string. We remember that the ResponseInterface extends the MessageInterface. So we can use the function and let Guzzle do the boring part.

Let’s test the server with our previous generated client.php script. Before we can test, we start the server.php with the internal PHP HTTP server:

Now run the client in a second console:

We should now the the output of our server:

In the next article we try to upload a file with the client to the server.

3 thoughts on “PSR-7 Standard – Part 3 – Response

Leave a Reply

%d bloggers like this: