This may be a daft question but I have been seeing and reading HTTP messages or PSR-7 in the current trend on PHP for development. Why out of a sudden we need HTTP message implementations in PHP for the modern web development?
For instance, with Slim 3, now we are to do this,
$app->get('/hello/{name}', function ($request, $response, $args) {
$response->write("Hello, " . $args['name']);
return $response;
});
We now must 'wrap' the request's result in the HTTP response object.
What is wrong with this old classic way of responding the request below?
echo 'Hello, ' . $_GET('name');
It is easier to understand for me.
What are the benefits of implementing HTTP messages? When do we need to use them? And why?
First thing, I'd recommend you to read section 3 of PSR-7 meta document.
I'll try to summarize some of the benefits of having a common set of interfaces for describing HTTP messages.
You could use superglobals variables (as $_GET
and $_POST
), but they are global mutable state. Along with this unit and integration testing of your code becomes hard.
For these reasons many PHP frameworks decided to implement an abstaction to represent HTTP messages (see for example Symfony HttpFoundation or Zend\Http).
This led to a situation where any application was based on a specific implementation of HTTP messages, so that it was hardly usable in projects built using other frameworks.
This is why a common set of interfaces helps abstract HTTP messages and work with them in a framework agnostic way.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments