Laravel URL Presenters
bakle
Posted on June 8, 2021
Usually, we always find new ways to make our backend code cleaner, readable and flexible by applying design patters, software principles, refactoring strategies, etc.
This time, the strategy we are going to apply is about communication of backend and frontend and how the backend code can provide much more information to our views.
Most of us render the application routes directly in the view, and sometimes we find that we are repeating these same routes along the view.
We can see that we are repeating the same url in lines #19 and #28. This is the good way, some people use (see line #2):
So, how can we make this a little bit cleaner and reusable along the application? Well, we can apply a Url Presenter.
There are many ways to do it, so I'm going to show you one of them.
Some people like to do it inside the model, which I think is not the best way because we are giving a responsibility to the model that should not have, I mean, why the model should know about urls?
Let's begin with the first step.
Creating an interface
When I talk about interface I mean that it could be an abstract class or interface, that depends on your need. This time we are going to make a simple interface for a url resource (index, show, edit, ...).
Creating concrete url presenter
Now, we just create a concrete url presenter, in this case we are going to create a UserUrlPresenter
Using the presenter
Let's suppose we have our UserController, we just have to pass the url presenter to the view.
Final view
Now, we can use the url presenter inside the view.
Bonus
I know I said that I am not a fan of url presenters inside the model, but I will give you an example of how to do it.
Creating the interface
Creating concrete url presenter
The presenter in the model
Using the presenter
Final View
Posted on June 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024