Implement a simple di container

I have seen many frameworks before, such as laravel, thinkphp, yii, etc. Basically, containers are used. For me, although I understand how laravel is written, if I don't try it, I still don't think it will be.

The following code is a simple container I implemented. It's not very good in many places, but it should be enough.

<?php

class Container{
    
    //$bindings is saved as a variable, which is the mapping of name = > instance
    private $binds = [];


    public static $instance = null;

    /**
     * Single case
     */
    public static function getInstance(){
        if(static::$instance == null){
            static::$instance = new static();
            return static::$instance ;
        }
        return static::$instance;
    }

    /**
     * At first, I was influenced by laravel, so I wrote a bind function,
     * After watching the container implementation of laravel, I can see that $concrete and $abstract transform back and forth.
     * The following code is a bit like the implementation in thinkphp, so it's easy to understand
     */
    public static function bind($name,$class = null){
        if($class instanceof Closure){
            static::getInstance()->binds[$name] = $class;
        }else if(is_object($class)){
            static::getInstance()->binds[$name] = $class;
        }else{
            //Starting to make an array here, laravel seems to be separated from make and build.
            static::getInstance()->make($name);
        }
        
    }

    /**
     * The core is the make method
     */
    public static function get($name){
        return static::getInstance()->make($name);
    }

    /**
     * Core make method
     */
    public function make($name){
        try{
            //Find whether the $this - > bindings instance already exists according to the class name. If it exists, return it directly
            if(array_key_exists($name,$this->binds)){
                return $this->binds[$name];
            }
            //Get its reflection class according to the class name
            $reflectClass = new ReflectionClass($name);
            //Using reflection classes
            $constructor = $reflectClass->getConstructor();
            //If there is no constructor, instantiate it directly
            $params = [];
            if(!is_null($constructor)){
                //Get methods in the constructor
                $constructorParams = $constructor->getParameters();
                // var_dump($constructorParams);
                //Save constructor parameters
                foreach($constructorParams as $constructorParam){
                    //This place is mainly to determine whether the parameter is a class. If it is constructed recursively, it is not simply added to $this - > params
                    if(!is_null($constructorParam->getType())){
                        $params[] =$this->make($constructorParam->name,$constructorParam->name);
                    }else{
                        $params[] = $constructorParam->name;
                    }
                }
            }
            //Construct an example here
            $class = $reflectClass->newInstanceArgs($params);
            //binding
            $this->binds[$name] = $class;
            return $class;
        }catch(ReflectionException $e){
            echo $e->getMessage();
        }
    }

    private function __construct(){}
    private function __clone(){}

}
?>

Here is my test file,

<?php

require "./Container.php";

class TestFather{
    private $name = "TestFather";

    public function __construct(){
        
    }
}

class Test extends TestFather{
    private $name = "Test";
    // public function __construct(DI $di, DI2 $di2,$name){
        
    // }
    public function __construct(DI $di,$name,$param_2 =[]){
    }

    public function sayName(){
        echo $this->name;
    }

    public function sayDI2Name(DI2 $di2){
        //If so, the di2 method prints out the previous string
        // echo "form Test say di2 name: ".$di2->sayName();
        echo "form Test say di2 name: ";
        echo $di2->sayName();
    }
}

class DI{
    private $name = "DI";
    public function __construct(DI2 $di2){}
    public function sayName(){
        echo $this->name;
    }    
}

class DI2{
    private $name = "DI2";
    public function __construct(){}
    
    public function sayName(){
        echo $this->name;
    }   
}

class DI3{
    private $name = "DI3";
    public function __construct(){}
    
    public function sayName(){
        echo $this->name;
    }   
}

class DI4{
    private $name = "DI4";
    public function __construct(){}
    
    public function sayName(){
        echo $this->name;
    }   
}

//It doesn't matter
// Container::bind('test','Test'); 
$test = Container::get('test');
$test->sayName();
echo "\n";
$test->sayDI2Name(new DI2());
echo "\n";

$di = Container::get('di');
$di->sayName();

echo "\n";
$di2 = Container::get('di2');
$di2->sayName();

echo "\n";
$di3 = new DI3();
Container::get('di3',$di3)->sayName();
echo "\n";
$di4 = function(){
    return new DI4();
};

Container::get('di4',$di4)->sayName();
echo "\n";


?>

The final result is as follows

Tags: PHP Laravel

Posted on Wed, 04 Dec 2019 14:52:31 -0800 by RaheimSG