Sunday, 15 September 2013

php - Default values in dependency injection -



php - Default values in dependency injection -

i have class tightly coupled dependencies, , class constructor doesn't have parameters. i'm trying able optionally pass in different dependencies without changing constructor signature , breaking applications utilize class.

i came pattern:

class auto { private $engine; public function __construct($options = array()) { if (isset($options['engine']) { $this->engine = $options['engine']; } else { $this->engine = new engine(); } } }

this way auto still created (with default engine) new car(), or passing in custom engine: new car(array('engine' => new customengine())).

is right way this? problems have maintainability?

this right pattern in opinion, utilize often.

dependency injection allows user of class provide dependencies. code, it's possible, don't see problem it.

the thing differently though utilize explicit parameters, can type-hint objects create sure of right class, , create easier know parameters can passed without looking @ code:

class auto { private $engine; public function __construct(engine $engine = null) { $this->engine = $engine ?: new engine(); } }

php oop dependency-injection

No comments:

Post a Comment