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. It is possible to mark an injection as optional:

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);
    }
}

If the injection would not be marked as optional and no binding would be defined for CoDriver retrieving the instance of BMWWithCoDriver would result in a stubbles\ioc\binding\BindingException. But by marking the injection as optional there will be no exception thrown and the instance of BMWWithCoDriver will be created without setting the codriver property.

Clone this wiki locally