Refactor Shared Variables on Blade Template View
2023-12-08 09:00 WIB - Hendrik Lie
We are getting addicted of having universal functions available for
all views. At first we only use that for our
App\Providers\AppServiceProvider to provide variable
$navbars. It works perfectly and we don’t even have to
think about it. However it occurred to me lately that we can have
more:
- Universal list of items
- Anonymous functions
Let us explore each of them.
Universal list of items
At first my approach was to basically make our
App\Providers\AppServiceProvider fetches recent blog posts
and latest news (variable $recentBlogs and
$latestNews respectively). It results in almost no way of
customizing how much of each of them to be fetched, and when to fetch
each of them. Basically we get all or nothing kind of deal, where ALL
VIEWS would have this variable lingering about.
We wanted to improve that, and indeed we did find a better solution.
Anonymous functions
Instead of passing $recentBlogs and
$latestNews, we can get an anonymous function
$fetchPosts($type, $limit). Therefore we would always have
this function lingering about.
However, unlike our previous approach, this one is actually useful. We can use it to basically fetch recent posts of type of our choosing, and of amount we specified. We have gained more control and flexibility on when to actually fetch items from database.
We didn’t stop there to make a list of posts. Other than
$fetchPosts($type, $limit), we also specified more
anonymous functions:
$fetchPost($slug)to fetch an individual published post item based on theirslug. This function should basically return aPostmodel that we can morph according to our needs. It can potentially remove the need of passingPostobjects directly from our controller.$fetchPostById($id)to fetch any post item given only theirid. Like$fetchPost($slug), but with this we can also obtain unpublished posts, as long as we know its specific ID. It can potentially be used for our landing page or any page we might need. It can also potentially be used for our footer! With this the controller will only need to pass the specific ID of our preferred footer.$carbon($timestring)to generate a Carbon date instance of$timestring. If no$timestringis given, it will use current time instead. We can then use it to format date and time according to our needs on each view.
Conclusion
Generating a universal list of posts might be useful if we will often use them on any view. However if we need to only use that in certain pages but not all of them, it would be a waste of resource. Instead of generating an universal list of posts, we might better use anonymous functions.
With anonymous functions stored in variables and then make them available to all views, we would have more flexibility and usability. It would significantly reduce code complexity and duplication by abstracting them into common utilities that we can use on demand.