当前位置: 首页 > 后端技术 > PHP

PHP通过反射自动注入参数

时间:2023-03-30 00:22:31 PHP

当前框架中有容器,容器通过反射解决依赖问题。首先说明一下工程文件结构:/ROOT_PATH├─src│├─Controllers││└─IndexController.php|├─Application.php(core,getinstance)│├─Http.php│└─Request.php│├─vendor│└─autoload.php│├─composer.json└─index.php我们要运行IndexController.php,而这个controller的构造函数需要一个Request类,Request类的构造函数需要一个Http类。IndexController.php类名;}}Application.phpisInstantiable()){thrownewException($class.'该类不可实例化');}//检查构造函数$rel_method=$rel_class->getConstructor();//如果没有构造函数,可以直接new这个类型if(is_null($rel_method)){returnnew$class();}//如果有构造函数,获取构造函数的参数$dependencies=$rel_method->getParameters();//处理,将传入的索引数组转为关联数组,key为函数参数名foreach($parametersas$key=>$value){if(is_numeric($key)){//删除索引数组,只保留关联数组unset($parameters[$key]);//使用参数的名称作为键$parameters[$dependencies[$key]->name]=$value;}}//处理依赖关系$actual_parameters=[];foreach($dependenciesas$dependenci){//获取对象名称,如果不是对象返回null$class_name=$dependenci->getClass();//获取变量的名称$var_name=$dependenci->getName();//如果是对象,然后递归newif(array_key_exists($var_name,$parameters)){$actual_parameters[]=$parameters[$var_name];}elseif(is_null($class_name)){//null不是对象,看是否有默认值,如果没有则抛出异常if(!$dependenci->isDefaultValueAvailable()){thrownewException($var_name.'参数没有默认值');$actual_parameters[]=$dependenci->getDefaultValue();}else{$actual_parameters[]=self::make($class_name->getName());}}//获取到构造函数的数组后,就可以实例化了return$rel_class->newInstanceArgs($actual_parameters);}}HTTP。phpclassNa我=__CLASS__;}}Request.phpclassName=__CLASS__;$this->className=$this->className。'->'。$http->类名;}}index.phpWaitmoonman\Reflex\HttpF:\phpStudy\WWW\reflex\index.php:12:object(Waitmoonman\Reflex\Controllers\IndexController)[9]这是上面一个完整的反射类动态注入参数的例子代码可以查看我的git仓库