In Magento 2, implementing service classes should take the place of old helper classes.
The reason is simple: helpers are unspecialized classes that tend to have too many responsibilities. For this reason, helpers also tend to have a name that doesn’t reveal a clear intent.
What’s a service class
A service class is a class with a single clear responsibility.
Usually, we can achieve this by implementing a single public method, typically named
Some examples taken from Magento codebase are:
What about the popular config helpers?
One of the typical implementation scenarios for helpers, especially in Magento 1 and in Magento 2 legacy code, is the helper used to retrieve configuration values.
When we need to access configuration values, better inject
which gives access to configuration values.
For convenience and reusability, we can declare configuration paths as constants into service interfaces.
We can also implement configuration service classes, like
for a couple of reasons:
- to expose a specific configuration which is subject to additional logic, or
- to make it easier to customize, e.g., through a plugin.