laravel依赖注入浅析
laravel容器包含控制反转和依赖注入,使用起来就是,先把对象bind好,需要时可以直接使用make来取就好。 通常我们的调用如下。 $config = $container->make('config');
$connection = new Connection($this->config);
比较好理解,这样的好处就是不用直接 new 一个实例了,方法传值没啥改变,还可以多处共享此实例。 但这跟依赖注入有什么关系,真正的依赖注入是不需给方法传递任何参数值,只需要指明方法参数类型,代码自动查找关系依赖自动注入。 这个特性在 laravel 的 Controller、Job 等处可以体现,如下: class TestController extends Controller {
public function anyConsole(Request $request,Auth $input) {
//todo
}
}
我们来看下他是怎么实现自动依赖注入的: 由
public function run(Request $request) {
$this->container = $this->container ?: new Container;
try {
if (! is_string($this->action['uses'])) {
return $this->runCallable($request);
}
if ($this->customDispatcherIsBound()) {
return $this->runWithCustomDispatcher($request);
}
return $this->runController($request);
} catch (HttpResponseException $e) {
return $e->getResponse();
}
}
判断 protected function runController(Request $request) {
list($class,$method) = explode('@',$this->action['uses']);
$parameters = $this->resolveClassMethodDependencies(
$this->parametersWithoutNulls(),$class,$method
);
if (! method_exists($instance = $this->container->make($class),$method)) {
throw new NotFoundHttpException;
}
return call_user_func_array([$instance,$method],$parameters);
}
protected function resolveClassMethodDependencies(array $parameters,$instance,$method) {
if (! method_exists($instance,$method)) {
return $parameters;
}
return $this->resolveMethodDependencies(
$parameters,new ReflectionMethod($instance,$method)
);
}
下面跳转到 public function resolveMethodDependencies(array $parameters,ReflectionFunctionAbstract $reflector) {
$originalParameters = $parameters;
foreach ($reflector->getParameters() as $key => $parameter) {
$instance = $this->transformDependency(
$parameter,$parameters,$originalParameters
);
if (! is_null($instance)) {
$this->spliceIntoParameters($parameters,$key,$instance);
}
}
return $parameters;
}
通过反射类方法得到类参数数组,然后遍历传递给 protected function transformDependency(ReflectionParameter $parameter,$originalParameters)
{
$class = $parameter->getClass();
if ($class && ! $this->alreadyInParameters($class->name,$parameters)) {
return $this->container->make($class->name);
}
}
终于看到了容器的影子,没错最终对象还是通过容器的 总结: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |