From 61f500e40b2b48071ad4f084ea5537d5199f07db Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Wed, 12 Jul 2023 22:35:12 +0100 Subject: [PATCH] daily-email: add 2023-07-05 Services vs Actions --- src/content/daily-email/2023-07-05.md | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/content/daily-email/2023-07-05.md diff --git a/src/content/daily-email/2023-07-05.md b/src/content/daily-email/2023-07-05.md new file mode 100644 index 000000000..b23b12876 --- /dev/null +++ b/src/content/daily-email/2023-07-05.md @@ -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.