Skip to content
This repository was archived by the owner on Jan 16, 2019. It is now read-only.

Optional injection

Frank Kleine edited this page Apr 4, 2015 · 5 revisions

Optional injection

Probably you do not want to inject an object every time, because the class will work fine without the dependency. If a parameter has a default value and is optional injection will be done using the default value.

class BMWWithCoDriver extends BMW {
    protected $codriver;

   /**
    * @Inject
    */
    public function __construct(Engine $engine, Tire $tire, CoDriver $codriver = null) {
        parent::__construct($engine, $tire);
        $this->codriver = $codriver;
    }

    public function moveForward($miles) {
        if (null !== $this->codriver) {
            $this->codriver->sayHello();
        }
        
        parent::moveForward($miles);
    }
}
Clone this wiki locally