Credit where is due. Last year I stumbled upon an article of Josip Crnković, in which he walked through some of the useful interfaces the framework has. In it, he discovers some that are used to send a Response to the browser.
After giving them a shot, I have to say these alleviates a lot of DRY problems and slims down multiple lines of code to just a few. In this series of articles I will check them out, as these may help you to code more easily your application.
How the framework checks the Response
The great tip bits are in the Router class. The
toResponse() method is responsible of checking what the controller returns, and create a Response from it.
It will cycle for every type instance possible, but we can resume this in four points:
- If it’s a
Responsableinstance, let the class handle the Response content entirely and call it a day.
- If it’s a PSR-compatible Response, create the Response.
- Okay, then it may be something that may be casted to JSON, so it will create a
JsonResponse. If it is an Eloquent Model, add the HTTP 201 code if it was created recently.
- Fine, it the response is anything, ANYTHING, that is not a Symfony Response will be casted as a normal Response.
How the Response checks the type
As we can see, first it will check if the content should be JSON, something that will be true if is an instance of
JsonSerializable, or just a simple
array. In any of these case, the content will be transformed to JSON, and it will set the
Content header as
The latter is done because you may make a normal Response but include a class that should be JSON-able, it will not transform the Response instance to a
JsonResponse. Don’t worry, you are not missing too much.
If not, it will check if is an instance of
Renderable, meaning that the whole content should be handled by the class instance, and will call the
render() method and set the whole content for the Response.
Finally it will try to cast the content (whichever it may be) it as a string. If it can’t, then it will fail miserably.
The framework will push out the Response and the browser will see it. And that’s it. Good night.