Martin Joo
Martin Joo

@mmartin_joo

8 Tweets 5 reads Feb 18, 2022
đź’ˇThis is a simple service class.
It helps you:
- Simplifying your overcomplicated controllers
- Extracting out reusable code
They can be really useful in smaller projects.
đź§µKeep Reading
1/7
This example is a Todo service for the Todo model. You can write any function that deals with todos, such as:
- Creating a new one
- Returning every todo that due today
- Deleting a todo (it can be more complex than a one-liner you know)
2/7
But you don’t need a 1-to-1 mapping between models and services. Let’s say you have a lot of logic about how and when to notify users.
You can move this logic into a TodoNotificationService:
3/7
And of course, you can write services to wrap 3rd parties:
4/7
Using a service is very easy. All you need to do is inject it into the controller:
5/7
Since a service is independent of the environment you can easily re-use it in a console command:
6/7
In general, services provide you a great way to:
- Unload some logic from the controllers
- Extract out re-usable pieces of code
- Structure your code in a good way
7/7
However, I personally like Actions better in larger applications.
If you’re interested in this topic subscribe to my DDD newsletter where I discuss these concepts. One e-mail every Wednesday until I finish the course I’m working on.
ddd-laravel.martinjoo.dev

Loading suggestions...