I currently have a class with tightly coupled dependencies, and the class constructor doesn't currently have any parameters. I'm trying to be able to optionally pass in different dependencies without changing the constructor signature and thus breaking applications that currently use the class.
I came up with this pattern:
class Car {
private $engine;
public function __construct($options = array()) {
if (isset($options['engine']) {
$this->engine = $options['engine'];
} else {
$this->engine = new Engine();
}
}
}
This way Car could still be created (with a default engine) with new car()
, or by passing in a custom engine: new Car(array('engine' => new CustomEngine()))
.
Is this a correct way to do this? What problems does this have with maintainability?