当前位置:网站首页>Dependency injection in PHP reflection implementation framework

Dependency injection in PHP reflection implementation framework

2022-06-25 19:16:00 kankan231

In the use of tp perhaps lavarel And other frameworks will see technologies such as dependency injection , It's actually used PHP The dynamic creation of object instances is realized by the reflection mechanism of , Let's simulate , The code is as follows :


/**
*
*  Tool class , Use this class to implement automatic dependency injection .
*
*/
class Ioc {
 
    //  Gets the object instance of the class 
    public static function getInstance($className) {
 
        $paramArr = self::getMethodParams($className);
        
        return (new ReflectionClass($className))->newInstanceArgs($paramArr);
    }
 
    /**
     *  Methods that execute classes 
     * @param  [type] $className  [ Class name ]
     * @param  [type] $methodName [ Method name ]
     * @param  [type] $params     [ Additional parameters ]
     * @return [type]             [description]
     */
    public static function make($className, $methodName, $params = []) {
 
        //  Get an instance of the class 
        $instance = self::getInstance($className);
 
        //  Get the parameters of dependency injection required by the method 
        $paramArr = self::getMethodParams($className, $methodName);
        
        $ret = $instance->{$methodName}(...array_merge($paramArr, $params));
        
        return $ret;
    }
 
    /**
     *  Get the method parameters of the class , Only get parameters of type 
     * @param  [type] $className   [description]
     * @param  [type] $methodsName [description]
     * @return [type]              [description]
     */
    protected static function getMethodParams($className, $methodsName = '__construct') {
 
        //  This class is obtained by reflection 
        $class = new ReflectionClass($className);
        $paramArr = []; //  Record parameters , And parameter types 
 
        //  Determine whether the class has this method 
        if ($class->hasMethod($methodsName)) {
            //  Get this method 
            $method = $class->getMethod($methodsName);
 
            //  Determine whether the method has parameters 
            $params = $method->getParameters();
 
            if (count($params) > 0) {
 
                //  Judge parameter type 
                foreach ($params as $key => $param) {
                    
                    if ($paramClass = $param->getClass()) {
                        
                        //  Get the parameter type name 
                        $paramClassName = $paramClass->getName();
 
                        //  Get parameter type 
                        $args = self::getMethodParams($paramClassName);
                        $paramArr[] = (new ReflectionClass($paramClass->getName()))->newInstanceArgs($args);
                    }
                }
            }
        }
 
        return $paramArr;
    }
}

//User controller 
class UserController{
    public function detail(Request $req){
        echo $req->param('id');
    }
}

// Request class 
class Request{

    protected $params = [
        'id' => 100,
    ];

    public function param($name){
        return isset($this->params[$name]) ? $this->params[$name] : null;
    }
}

// call UserController->detail() Method 
try {
    Ioc::make(UserController::class,'detail');
} catch (\Exception $th) {
    echo $th->getMessage();
}

原网站

版权声明
本文为[kankan231]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202190519260102.html