I'm writing a PHP application with testability in mind, so my classes always ask in their constructors for the "collaborator objects" they depend on, in respect to the Dependency Injection pattern.
That way, I'm able to pass in mocks or test implementations in my unit tests.
What I want to achieve though, is to be able to instantiate a class with null values passed to its constructor arguments, in order to trigger a fallback mechanism which instantiates a default implementation class for each collaborator.
Because object-type parameters cannot be given a default value in PHP, I have to do it inside the constructor. The following code is an example of the approach I'm currently using :
public function __construct(ResourceLoader $loader = null, Logger $logger = null)
if ($loader == null) $loader = new DefaultResourceLoader;
if ($logger == null) $logger = new DefaultLogger;
$this->loader = $loader;
$this->logger = $logger;
What do you think of this ? Should I use an IoC container instead or is there another way of giving object-type arguments a default value ?
posted date: 2008-12-17 18:33:00