在生成Laravel控制器或成员方法中,可以通过以下类型约束来使用依赖关系注入
publicfunctionstore (请求$请求) )
{
//待办事宜
}
其中$Request参数使用类型约束。 request是类型约束的类型,是类。 illuminate http请求。
本文研究Laravel的依赖注入原理,为什么这样定义不需要实例化就可以直接使用Request的方法呢? 既然框架只是实例化并加入我们,我们来看看这个过程。
1 .路由定义
从源位置看,在路由定义文件中定义了这样的路由。
route:3360resource((/role )、) admin(rolecontroller );
这是基于资源的路由,Laravel会自动生成用于添加/删除检查的路由入口。
本论文开头的store方法是控制器的方法,从图中可以看出,路由定义的Action也是apphttpcontrollersadminrolecontroller @ store
解决路由选择方法
根据路由定义找到控制器和方法。 此过程通过dispatch方法实现。
(文件: vendor/laravel/framework/src/illuminate/routing/controller dispatcher.PHP )
publicfunctiondispatch (路由$路由,$控制器,$方法() ) ) ) ) ) ) 65
{
$ parameters=$ this-resolveclassmethoddependencies (
$route-parametersWithoutNulls ()、$controller、$method
);
if(method_exists($controller,' callAction ' ) )。
返回$控制器-呼叫操作($ method,$parameters );
}
返回$控制器- { $ method } (array _ values ) $parameters );
}
其中,resolveClassMethodDependencies方法" yjddbmh "的作用是从类的方法中检索依赖对象。
protectedfunctionresolveclassmethoddependencies (阵列$参数,$实例,$方法) ) ) )。
{
if (! method_exists($instance,$method ) )
返回$ parameters;
}
返回$ this-resolvemethoddependencies (
$parameters,newreflectionmethod($instance,$method )。
);
}
这里重要的是使用了PHP的反射。 请注意RelectionMethod方法。 可以获取类的方法参数列表,并知道参数的类型约束、参数名称等。
其中的$instance参数是RoleController控制器类,$method参数是方法名称strore。
2 .获取依存对象的示例
通过从方法的参数中获取依存对象的约束类型,可以实例化该依存对象。
protectedfunctiontransformdependency (反射参数$parameters,$parameters ) )。
{
$class=$parameter-getClass (;
//iftheparameterhasatype-hinted class,wewillchecktoseeifitisalreadyin
//thelistofparameters.ifitiswewilljustskipitasitisprobablyamodel
//bindingandwedonotwanttomesswiththose; otherwise,we resolve it here。
if ($class! $ this-alreadyinparameters ($ class-name,$parameters ) )
返回$ parameter-isdefaultvalueavailable (
? $parameter-getDefaultValue (
3360 $ this-container-make ($ class-name );
}
}
根据类名从容器中检索对象。 绑定此对象实例的过程是在服务提供器中首先定义和定义的。
然后,将实例化对象传递给store方法,以便可以使用依赖对象。
3 .关于PHP反射
举个使用ReflectionMethod的例子吧。
类演示
{
隐私$请求;
publicfunctionstore (请求$请求) )
{
}
}
打印newreflectionmethod (demo :3360 class、“‘store”)的内容如下。
可以获得该方法的参数列表、参数的约束类型,例如typeHint、IlluminateHttpRequest。
根据类名,可以从容器中检索服务提供者第一个绑定的实例。