daily-email: add 2023-07-05
Services vs Actions
This commit is contained in:
parent
ecf221868b
commit
61f500e40b
1 changed files with 46 additions and 0 deletions
46
src/content/daily-email/2023-07-05.md
Normal file
46
src/content/daily-email/2023-07-05.md
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
---
|
||||||
|
title: >
|
||||||
|
Services vs Actions
|
||||||
|
pubDate: 2023-07-05
|
||||||
|
permalink: >
|
||||||
|
archive/2023/07/05/services-vs-actions
|
||||||
|
tags:
|
||||||
|
- software-development
|
||||||
|
- software-architecture
|
||||||
|
---
|
||||||
|
|
||||||
|
When creating a custom module, where do you put your business logic?
|
||||||
|
|
||||||
|
You want to keep classes like Controllers and Commands simple and move any reusable logic into separate files.
|
||||||
|
|
||||||
|
Usually, this means 'Service' classes, but another approach I like is to use 'Action' classes.
|
||||||
|
|
||||||
|
## What is an Action class?
|
||||||
|
|
||||||
|
An Action is a PHP class representing a single action that must be performed.
|
||||||
|
|
||||||
|
It usually contains a single method with a descriptive name summarising the task, such as `GetAccessToken`.
|
||||||
|
|
||||||
|
This differs from a generic service like `ApiService` with multiple methods like `getAccessToken()`.
|
||||||
|
|
||||||
|
## Using Action classes
|
||||||
|
|
||||||
|
I'll register Action classes in the service container to use dependency injection and autowiring and easily inject the Action into other classes that need it, like Controllers and Commands.
|
||||||
|
|
||||||
|
If you need multiple implementations, multiple actions can implement the same Interface and make them swappable, such as having `GetAccessToken` and `GetAndCacheAccessToken` implement the same `GetsAccessToken` interface.
|
||||||
|
|
||||||
|
That also enables using design patterns like Decorators with Actions.
|
||||||
|
|
||||||
|
## Why I like Actions
|
||||||
|
|
||||||
|
I like more readable and meaningful class names and prefer working with multiple simpler classes than those with fewer complex ones.
|
||||||
|
|
||||||
|
I like leveraging design patterns I'm used to, such as the Decorator pattern, by having common interfaces and contracts.
|
||||||
|
|
||||||
|
I like that if I need to add another implementation, I can add it without changing the existing code, so it follows the SOLID principles.
|
||||||
|
|
||||||
|
## What about you?
|
||||||
|
|
||||||
|
Do you use Action classes in your code, or do you use Services or something else?
|
||||||
|
|
||||||
|
Reply to this email and let me know.
|
Loading…
Add table
Add a link
Reference in a new issue