A pattern suggestion to integrate framework independent domain models into Magento.
We want to instantiate a domain model based on Magento configuration.
We create a new Magento specific implementation of the domain model's interface, which acts like a decorator around the original model, passing through all method calls.
It comes with its own private factory method to instantiate the original domain model once, with arguments taken from the Magento configuration (ScopeConfigInterface
).
This implementation is then configured as preference for the interface, so that any client code that needs this configured object, can request it via constructor injection.
See attached code. A TvSpotSchedule
model, that needs to be constructed from configuration in Magento.
Now any class that needs access to the schedule can use it like this:
public function __construct(TvSpotScheduleInterface $tvSpotSchedule)
- Extensibility: Pure Domain models should not need the full extensibility with plugins. The Magento implementation could still be replaced via preference to use a different factory method. However, in the scope of public extensions or core code, where maximum flexibility is a priority, the object manager could be used instead of
new
or static constructor methods.
A typical implementation would be a factory class with createFromConfig()
method (or just create()
, taking default argument values from configuration).
Drawback: Everywhere we want to use the model, we need to inject the factory and create a new instance from it. This adds another layer of indirection in client code, and also using a shared instance is not possible.