Sunday, July 5, 2015

PHP Dependancy Injection

This two scripts show Motor class as dependency that is injected in Car class.

<?php
class Motor {
    public function startEngine(){
        echo 'engine has started';
    }
}

class Car {
    public function __construct(Motor $m){
        $m -> startEngine();
    }
}

$a = new Car(new Motor());
?>

and second example

<?php
class Motor {
    public function __construct(){
        echo 'engine has started';
    }
}

class Car {
    public function __construct(){
        $m = new Motor();
    }
}

$a = new Car();
?>

The point is that instancing of dependent class is not done in client but in consumer class. 

No comments:

Post a Comment