Laravel服务容器绑定与解析机制详解
前言
坦白讲,初次接触 Laravel 框架手册时,由于缺乏相关经验,入门门槛显得颇为陡峭。尽管目前对部分深层架构尚未完全掌握,但通过公司项目的实际开发,已逐渐熟悉依赖注入、ORM 操作及用户认证等核心业务功能。然而,对于服务提供器、服务容器、中间件等基础架构组件,因前期已由团队配置完毕,实际操作经验相对较少,导致阅读官方文档时仍感困惑。因此,结合网络资源的学习心得,本文旨在梳理 Laravel 核心架构中的关键概念,以辅助后续的手册阅读。推荐参考网站:https://laraweb.net/,该日本站点内容适合新手,借助浏览器翻译即可顺畅理解。
关于服务容器
官方手册定义:Laravel 服务容器是用于管理类的依赖和执行依赖注入的工具。所谓“依赖注入”,实质是指类的依赖项通过构造函数或特定的「setter」方法被注入到类中。简而言之,服务容器是一种管理机制,负责管理类(即服务)的实例化过程。下文将直接展示其具体用法。
1.在服务容器中注册类(bind)
$this->app->bind('sender','MailSender');
//$this->app成为服务容器。
2.从服务容器生成类(make)
$sender = $this->app->make('sender');
//从服务容器($this->app)创建一个sender类。
在此场景下,系统将返回 MailSender 类的实例。
这是服务容器最基础的使用示例,接下来将对服务容器进行更深入的详细介绍。
laravel容器基本认识
应用启动初期,index.php 文件首先加载由 Composer 生成的自动加载器,随后从 bootstrap/app.php 脚本中获取 Laravel 应用程序实例。Laravel 执行的首要动作便是创建一个 application/service container 实例。
$app = new Illuminate\Foundation\Application(
dirname(__DIR__)
);
该文件在每次请求到达 Laravel 框架时均会执行,所创建的 $app 即为 Laravel 框架的应用程序实例,它在整个请求生命周期中保持唯一性。Laravel 提供了包括认证、数据库、缓存、消息队列在内的众多服务,$app 作为容器管理工具,负责几乎所有服务组件的实例化及其生命周期管理。当需要某个服务类来完成特定功能时,只需通过容器解析出该类型的一个实例即可。从最终使用视角来看,Laravel 容器对服务实例的管理主要涵盖以下四个方面:
- 服务的绑定与解析
- 服务提供者的管理
- 别名的作用
- 依赖注入
在深入学习上述四个关键点之前,首先需要了解如何在代码中获取容器实例。
如何在代码中获取到容器实例
第一种方式是调用全局辅助函数 app()。
$app = app();
//app这个辅助函数定义在\vendor\laravel\framework\src\Illuminate\Foundation\helper.php
该函数定义在 \vendor\laravel\framework\src\Illuminate\Foundation\helper.php 文件中,并通过 Composer 自动加载至项目中。
因此,在处理 HTTP 请求的任何代码位置,均可访问此类辅助函数,例如 app()。
第二种方式是使用 Facade(门面)模式。
Route::get('/', function () {
dd(App::basePath());
return '';
});
//这个其实是用到Facade,中文直译貌似叫门面,在config/app.php中,
在 config/app.php 配置文件中,存在一个 aliases 数组专门用于配置类型别名,其中第一个即为 'App' => Illuminate\Support\Facades\App::class。
关于 Laravel 门面的具体实现机制,建议查阅相关资料深入了解。
第三种方式是在服务提供者内部直接使用 $this->app。
服务提供者将在后文详细阐述,此处仅作引入。由于服务提供者类均由 Laravel 容器实例化,且它们继承自 Illuminate\Support\ServiceProvider,该类定义了一个实例属性 $app。
abstract class ServiceProvider
{
protected $app;
Laravel 在实例化服务提供者时,会将 Laravel 容器实例注入到该 $app 属性上。因此,在服务提供者内部,始终可以通过 $this->app 访问 Laravel 容器实例,而无需再使用 app() 函数或 App Facade。
如何理解服务绑定与解析
从浅层含义理解,既然容器用于存储对象,便必然涉及对象的存入与取出过程。这一存入与取出的过程在 Laravel 中被称为服务的绑定与解析。
app()->bind('service', 'this is service1');
app()->bind('service2', [
'hi' => function(){
//say hi
}
]);
class Service {
}
app()->bind('service3', function(){
return new Service();
});
此外,还有一种单例绑定 singleton,它是 bind 的一种特殊情况(第三个参数为 true)。绑定到容器的对象仅会被解析一次,后续的调用均返回相同的实例。
public function singleton($abstract, $concrete = null)
{
$this->bind($abstract, $concrete, true);
}
在绑定时,可以直接绑定已初始化的数据(如基本类型、数组、对象实例),也可以使用匿名函数进行绑定。使用匿名函数的优势在于,服务绑定到容器后并不会立即产生最终的服务对象,只有在该服务被解析时,匿名函数才会执行,从而生成对应的服务实例。
实际上,当我们使用 singleton、bind 方法以及数组形式(这三种均为后续介绍的绑定方法)进行服务绑定时,如果绑定的服务形式不是匿名函数,Laravel 内部也会用一个匿名函数将其包装起来。这样,无论绑定何种内容,都能实现前述的懒初始化功能,这对容器性能有益。这一点可以从 bind 的源码细节中得到印证。
if (! $concrete instanceof Closure) {
$concrete = $this->getClosure($abstract, $concrete);
}
看看bind的底层代码
public function bind($abstract, $concrete = null, $shared = false)
第一个参数为服务绑定名称,第二个参数为服务绑定的结果(即闭包,用于获取实例),第三个参数表示该服务在多次解析时是否始终返回第一次解析出的实例(即单例绑定 singleton)。
服务绑定还可以通过数组的方式实现。
app()['service'] = function(){
return new Service();
};
绑定操作大致如此,接下来看解析,即从容器中取出并使用。
$service= app()->make('service');
该方法接收两个参数:第一个是服务的绑定名称或服务绑定名称的别名;若传入的是别名,则会根据别名配置找到最终的服务绑定名称,进而进行解析;第二个参数是一个数组,最终将传递给服务绑定产生的闭包。
看源码:
/**
* Resolve the given type from the container.
*
* @param string $abstract
* @param array $parameters
* @return mixed
*/
public function make($abstract, array $parameters = [])
{
return $this->resolve($abstract, $parameters);
}
/**
* Resolve the given type from the container.
*
* @param string $abstract
* @param array $parameters
* @return mixed
*/
protected function resolve($abstract, $parameters = [])
{
$abstract = $this->getAlias($abstract);
$needsContextualBuild = ! empty($parameters) || ! is_null(
$this->getContextualConcrete($abstract)
);
// If an instance of the type is currently being managed as a singleton we'll
// just return an existing instance instead of instantiating new instances
// so the developer can keep using the same objects instance every time.
if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
return $this->instances[$abstract];
}
$this->with[] = $parameters;
$concrete = $this->getConcrete($abstract);
// We're ready to instantiate an instance of the concrete type registered for
// the binding. This will instantiate the types, as well as resolve any of
// its "nested" dependencies recursively until all have gotten resolved.
if ($this->isBuildable($concrete, $abstract)) {
$object = $this->build($concrete);
} else {
$object = $this->make($concrete);
}
// If we defined any extenders for this type, we'll need to spin through them
// and apply them to the object being built. This allows for the extension
// of services, such as changing configuration or decorating the object.
foreach ($this->getExtenders($abstract) as $extender) {
$object = $extender($object, $this);
}
// If the requested type is registered as a singleton we'll want to cache off
// the instances in "memory" so we can return it later without creating an
// entirely new instance of an object on each subsequent request for it.
if ($this->isShared($abstract) && ! $needsContextualBuild) {
$this->instances[$abstract] = $object;
}
$this->fireResolvingCallbacks($abstract, $object);
// Before returning, we will also set the resolved flag to "true" and pop off
// the parameter overrides for this build. After those two things are done
// we will be ready to return back the fully constructed class instance.
$this->resolved[$abstract] = true;
array_pop($this->with);
return $object;
}
第一步:
$needsContextualBuild = ! empty($parameters) || ! is_null(
$this->getContextualConcrete($abstract)
);
该方法主要用于区分解析的对象是否带有参数。若有参数,需对参数做进一步分析,因为传入的参数也可能涉及依赖注入,故需对传入参数进行解析;这部分细节将在后文分析。
第二步:
if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
return $this->instances[$abstract];
}
如果是绑定的单例,且不需要上述的参数依赖,则可直接返回 $this->instances[$abstract]。
第三步:
$concrete = $this->getConcrete($abstract);
...
/**
* Get the concrete type for a given abstract.
*
* @param string $abstract
* @return mixed $concrete
*/
protected function getConcrete($abstract)
{
if (! is_null($concrete = $this->getContextualConcrete($abstract))) {
return $concrete;
}
// If we don't have a registered resolver or concrete for the type, we'll just
// assume each type is a concrete name and will attempt to resolve it as is
// since the container should be able to resolve concretes automatically.
if (isset($this->bindings[$abstract])) {
return $this->bindings[$abstract]['concrete'];
}
return $abstract;
}
此步骤主要从绑定的上下文中查找是否能找到绑定类;若未找到,则再从 $bindings[] 中查找关联的实现类;若仍未找到,则直接返回 $abstract 本身。
// We're ready to instantiate an instance of the concrete type registered for
// the binding. This will instantiate the types, as well as resolve any of
// its "nested" dependencies recursively until all have gotten resolved.
if ($this->isBuildable($concrete, $abstract)) {
$object = $this->build($concrete);
} else {
$object = $this->make($concrete);
}
...
/**
* Determine if the given concrete is buildable.
*
* @param mixed $concrete
* @param string $abstract
* @return bool
*/
protected function isBuildable($concrete, $abstract)
{
return $concrete === $abstract || $concrete instanceof Closure;
}
如果之前找到的 $concrete 返回的是 $abstract 值,或者 $concrete 是一个闭包,则执行 $this->build($concrete);否则,表示存在嵌套依赖的情况,则采用递归的方法执行 $this->make($concrete),,直到所有依赖解析完毕为止。
$this->build($concrete)
/**
* Instantiate a concrete instance of the given type.
*
* @param string $concrete
* @return mixed
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
public function build($concrete)
{
// If the concrete type is actually a Closure, we will just execute it and
// hand back the results of the functions, which allows functions to be
// used as resolvers for more fine-tuned resolution of these objects.
// 如果传入的是闭包,则直接执行闭包函数,返回结果
if ($concrete instanceof Closure) {
return $concrete($this, $this->getLastParameterOverride());
}
// 利用反射机制,解析该类。
$reflector = new ReflectionClass($concrete);
// If the type is not instantiable, the developer is attempting to resolve
// an abstract type such as an Interface of Abstract Class and there is
// no binding registered for the abstractions so we need to bail out.
if (! $reflector->isInstantiable()) {
return $this->notInstantiable($concrete);
}
$this->buildStack[] = $concrete;
// 获取构造函数
$constructor = $reflector->getConstructor();
// If there are no constructors, that means there are no dependencies then
// we can just resolve the instances of the objects right away, without
// resolving any other types or dependencies out of these containers.
// 如果没有构造函数,则表明没有传入参数,也就意味着不需要做对应的上下文依赖解析。
if (is_null($constructor)) {
// 将 build 过程的内容 pop,然后直接构造对象输出。
array_pop($this->buildStack);
return new $concrete;
}
// 获取构造函数的参数
$dependencies = $constructor->getParameters();
// Once we have all the constructor's parameters we can create each of the
// dependency instances and then use the reflection instances to make a
// new instance of this class, injecting the created dependencies in.
// 解析出所有上下文依赖对象,带入函数,构造对象输出
$instances = $this->resolveDependencies(
$dependencies
);
array_pop($this->buildStack);
return $reflector->newInstanceArgs($instances);
}
总结
以上所述是小编给大家介绍的Laravel服务容器的绑定与解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对本站网站的支持! 如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!