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.
- Oliver
Was this interesting?
About me
I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.