Changes between Initial Version and Version 1 of Docs/IOC/OptionalInjection

Show
Ignore:
Timestamp:
01/03/09 14:35:12 (20 months ago)
Author:
mikey (IP: 92.205.42.64)
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Docs/IOC/OptionalInjection

    v1 v1  
     1= Inversion of Control: Optional injection = 
     2 
     3Probably 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: 
     4 
     5{{{ 
     6#!php 
     7<?php 
     8class BMWWithCoDriver extends BMW { 
     9    protected $codriver; 
     10 
     11   /** 
     12    * @Inject(optional=true) 
     13    */ 
     14    public function setCoDriver(CoDriver $codriver) { 
     15        $this->codriver = $codriver; 
     16    } 
     17     
     18    public function moveForward($miles) { 
     19        if (null !== $this->codriver) { 
     20            $this->codriver->sayHello(); 
     21        } 
     22         
     23        parent::moveForward($miles); 
     24    } 
     25} 
     26?> 
     27}}} 
     28 
     29If 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 {{{stubBindingException}}}. 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.