Laravel: The Fantastic 4 Interfaces — Renderable
Leaning the Response code, one implementation at a time.
When in doubt: use a cat photo
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.
Renderable
The Renderable interface is like the Jsonable one, but instead of JSON, it this forces the class to have a render()
method for rendering it completely from top to bottom, like a Mail or a View.
When a Response is pushed out from the controller, you can set as content a Renderable class. The Response will use the render()
method to get the renderable content.
As you can see, the usefulness for this interface is relatively small. You could use this interface for classes that, for example, return a fully fledged HTML page without the help of a templating engine, or send partial HTML component via AJAX — in these cases it’s better to use JSON but if it’s only few things, there is no harm.
Example: Rendering an static page
In my Podcast, some podcast may be flagged by the community for different reasons. When they are taken down, we need return a full HTML static page.
Instead of using a conditional inside the Podcast view, we will just add it to the render()
method itself to the Podcast model. This is a very silly example, but is just for illustration.
Then, I can go into my Controller and just push the Podcast.
Of course, again, this is just an example. This is better suited for classes that compose multiple things, among some other niche examples. But you get the idea.