How is it done?
I have a Model class that is the parent to many sub-classes, and that Model depends on a database connection and a caching mechanism.
Now, this is where it starts getting troublesome: I have no control over how each object gets instantiated or used, but I have control over methods that get used by the sub-classes.
Currently I have resorted to using static methods and properties for dependency injection, as such:
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; } }
Which has worked out well, but it feels dirty (it creates a global state for all Models).
I have considered the factory pattern, but that removes the control of the instantiation from the sub-classes (how do I instantiate an object with a variable number of parameters in it's constructor?).
Now I am at a loss. Any help would be appreciated.