| | 1 | = Inversion of Control: Optional injection = |
| | 2 | |
| | 3 | 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: |
| | 4 | |
| | 5 | {{{ |
| | 6 | #!php |
| | 7 | <?php |
| | 8 | class 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 | |
| | 29 | 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 {{{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. |