I'm trying to design a set of factory classes for our system, where some objects created by the factory also need to be initialized before they can be used properly.
Example:
$foobar = new Foobar();
$foobar->init( $qux, ... );
// $foobar ready for usage
For the same of example, lets say that the $qux
object is the only dependency that Foobar
needs. What I'd like to get to is:
$foobar = Foo_Factory( 'bar' );
In order to avoid the need to pass along the $qux
object across the whole system and pass it to the factory class as another parameter, I'd like to perform initialization of Foobar
directly in the factory class:
class Foo_Factory {
public static function getFoo( $type ) {
// some processing here
$foo_name = 'Foo' . $type;
$foo = new $foo_name();
$foo->init( $qux );
return $foo;
}
}
There are few solutions that come to mind, but none of them is ideal:
- Add a static setter method for
$qux
to the factory class, and let it store a reference to$qux
in a private static variable. The system can set$qux
at the start, and the factory class can prevent any future changes (for security reasons).
Although this approach works, using a static parameter for storing reference to$qux
is problematic during unit testing (e.g. it happily lives survives between individual tests due to its static state). - Create a new context class using Singleton pattern and let the factory class use it to get a reference to
$qux
. This might be a bit cleaner way to do this than option #1 (although we move the static problem from the factory class to the context class). - Use dependency injection all the way, i.e. pass
$qux
to any object which uses the factory class, and let that object pass it along to the factory class as another parameter:Foo_Factory::getFoo($type, $qux);
. - Same as above (#3), but instead of passing
$qux
along the system, pass an instance of the factory class instead (i.e. in this case it would not be static, but instantiable).
What would you recommend please? Any of the four alternatives mentioned above, or is there a better way to do this please?
Note: I don't want to get into a static is evil
flamewar here, just trying to come up with the best solution.