Laravel 依赖注入基础概念
Laravel 的服务容器集成了控制反转(IoC)与依赖注入功能。其基本使用逻辑是先通过 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
}
}
依赖注入底层实现原理
接下来我们将探讨 Laravel 是如何实现这种自动依赖注入的。
请求首先由 index.php 调用 Kernel,经过多层 Kernel 管道处理,再传递给 Router,随后经过中间件管道的层层调用,最终定位到具体的路由处理逻辑。
具体代码位于 Illuminate/Routing/Route.php 的第 124 行附近。
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();
}
}
系统会判断 $this->action['uses'](格式如 \App\Http\Controller\Datacenter\RealTimeController@anyConsole)是否为字符串,并检查是否绑定了自定义路由分发器。如果满足条件,则跳转执行 $this->runController($request)。
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);
}
在 runController 内部,调用了 $this->resolveClassMethodDependencies 方法,从命名即可看出这是负责解析依赖的核心逻辑。该方法结合 $this->parametersWithoutNulls() 过滤空值,并将类名(如 \App\Http\Controller\Datacenter\RealTimeController)和方法名(如 anyConsole)作为参数传入。
protected function resolveClassMethodDependencies(array $parameters, $instance, $method)
{
if (! method_exists($instance, $method)) {
return $parameters;
}
return $this->resolveMethodDependencies(
$parameters, new ReflectionMethod($instance, $method)
);
}
此处通过 new ReflectionMethod($instance, $method) 获取类方法的反射对象,详细用法可参考 PHP 官方文档:http://www.php.net/manual/zh/class.reflectionmethod.php。
随后,执行流跳转到 Illuminate/Routing/RouteDependencyResolverTrait.php 的第 54 行。
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;
}
系统通过反射获取类方法的参数数组,并遍历每个参数传递给 $this->transformDependency 方法进行处理。如果无法获取对应的依赖实例,则会调用 $this->spliceIntoParameters 移除该参数。
protected function transformDependency(ReflectionParameter $parameter, $parameters, $originalParameters)
{
$class = $parameter->getClass();
if ($class && ! $this->alreadyInParameters($class->name, $parameters)) {
return $this->container->make($class->name);
}
}
此时可以看到容器的介入,最终依赖对象是通过容器的 make 方法实例化的。至此,参数列表构造完成,最终由 runController 方法中的 call_user_func_array 回调函数执行控制器方法。
关键注意事项与总结
总结上述过程:
1. 依赖注入的核心原理是利用 PHP 反射机制获取类方法的参数类型,随后利用容器构造出相应的实例,最后通过回调函数触发执行。
2. 被注入对象的构造函数不能包含参数,否则会导致报错 Missing argument 1。
3. 虽然依赖注入优势明显,但它必须由 Router 类发起调用才能生效。如果直接使用 new 方式实例化类,则无法实现自动注入。这也解释了为何只有 Controller 和 Job 等特定类才能享受这一特性。
以上就是关于 PHP + Laravel 依赖注入的全部知识点内容,感谢大家的学习和对本站的支持。