Using Laravel Controllers, Events, Listeners, Services and Validation Together!
Reza Khademi
Posted on July 16, 2022
We can put all codes of a web application into controllers but this action sounds crazy and it’s quite not right to do!
In this article we will see how to structure a web-app with a well-known pattern. I must say you can do below examples in other different ways and probably all of them will be right, So this article is just some examples for doing things!
Let me explain the scenario:
Imagine we have a simple medium-app and it will have a Content section which a user can share a blog post and his/her followers will notice when a new article published!
1. Ugly Way
Make a ArticleController
and put all codes in it, like below:
2. Better Way
First, we should replace Request $request an ArticleStoreRequest $request
to validate data in a better way:
php artisan make:request ArticleStoreRequest
Don’t forget to return true in authorize()
method, so user can do this action:
Second, we should make the ArticleService
to move creation logic from controller to service. Because the only thing that a controller will do is passing data!
So we will make ArticleService
in Services folder and write creation code to a simple related method and by considering Single Responsibility Principle move upload image to it’s method like below:
Let’s have another look at our ArticleController
again see what have been changed so far:
- Now let’s use Event and Listener for sending emails to followers of article writer:
php artisan make:event ArticlePublishedEventphp artisan make:listener ArticlePublishedListener --event=ArticlePublishedEvent
This philosophy help us to devide operations and the event will fire automatically when ever and where ever we want. Also this will pretend us to repeat ourselves!
The event class should accept the User model and Article model, which is then passed to ANY listener of that event:
Then, the Event is fired from the Controller, like this:
And, in the Listener class, we repeat the same logic:
That’s it…
Posted on July 16, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024