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

Optional injection

mikey179 edited this page Mar 4, 2012 · 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(optional=true)
    */
    public function setCoDriver(CoDriver $codriver) {
        $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 net\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