How to do it?
I have a Model class that is the parent of many subclasses, and this model depends on the database connection and the caching mechanism.
Now, when it starts to bother: I cannot control how each object gets an instance or is used, but I have control over the methods that are used by subclasses.
Currently, I have resorted to using static methods and properties for dependency injection:
class Model
{
private static $ database_adapter;
private static $ cache_adapter;
public static function setDatabaseAdapter (IDatabaseAdapter $ databaseAdapter)
{
self :: $ databaseAdapter = $ databaseAdapter;
}
public static function setCacheAdapter (ICacheAdapter $ cacheAdapter)
{
self :: $ cacheAdapter = $ cacheAdapter;
}
}
What happened well, but it feels dirty (it creates a global state for all models).
I looked at the factory pattern, but removes control of the instance from subclasses (how to create an instance of an object with a variable number of parameters in it constructor?).
Now I'm at a loss. Any help would be appreciated.
source
share