IOC container idea [PHP] items used in practice

1. container means is a global variable, which kept a lot of the object, if an object to use to get from the inside, the premise is to put objects into them
2. inversion of control is to own control to others
3. the combination of the two is, his own control to others and create an object into a global variable in
4 advantage is the flexibility to modify the properties of an object, without the need to modify the code for the class itself

Project practice:
Resources property array 1.Application object is the container
2.getResource control method is to generate the object to generate a control object to the Application
under here to simplify regulations 3., from the class definition must have createResource static method to create your own object

class Application{
    private $resources= array();
    public function getResource($class,$params) {
        if (!isset($this->resources[$class])) {
            $this->resources[$class] = call_user_func_array(array($class, 'createResource'), $params);
        }   
        return $this->resources[$class];
    }   
}

class User {
    private $name;
    private $age;
    public function __construct($name,$age){
        $this->name=$name;
        $this->age=$age;
    }   
    public static function createResource($name,$age) {
        return new self($name,$age);
    }   
    public function says(){
        echo $this->name;
    }   
}
$app=new Application();
$user=$app->getResource("User",array("taoshihan","1000"));
$user->says();

 

Guess you like

Origin www.cnblogs.com/taoshihan/p/11423263.html