laravel容器是什么?Laravel 效劳容器是什么?
在 Laravel 文档 中,有一段关于 Laravel 效劳容器的引见:
Laravel 效劳容器是用于管理类的依靠和实行依靠注入的东西。依靠注入这个花俏名词实质上是指:类的依靠项经由过程组织函数,或许某些情况下经由过程「setter」要领「注入」到类中。
划下重点,「Laravel 效劳容器」是用于 管理类的依靠 和 实行依靠注入 的 东西。
经由过程前一节「依靠注入基本概念」相干论述,我们不难得出如许一个简朴的结论「Laravel 效劳容器」就是「依靠注入容器」。
实在,效劳容器作为「依靠注入容器」去完成 Laravel 所需依靠的注册、绑定和剖析事情只是 「Laravel 效劳容器」中心功用之一;别的,「Laravel 效劳容器」还担纲 Laravel 运用的注册顺序的功用。
节选一段「深度发掘 Laravel 生命周期」一文中有关效劳容器的内容:
建立运用实例即实例化 Illuminate\Foundation\Application 这个效劳容器,后续我们称其为 APP 容器。在建立 APP 容器重要会完成:注册运用的基本途径并将途径绑定到 APP 容器 、注册基本效劳提供者至 APP 容器 、注册中心容器别号至 APP 容器 等基本效劳的注册事情。
所以要相识 Larvel 效劳容器必定须要研讨 Illuminate\Foundation\Application 的组织函数:
/**
* Create a new Illuminate application instance.
*
* @see https://github.com/laravel/framework/blob/5.6/src/Illuminate/Foundation/Application.php#L162:27
* @param string|null $basePath
* @return void
*/
public function __construct($basePath = null)
{
if ($basePath) {
$this->setBasePath($basePath);
}
$this->registerBaseBindings();
$this->registerBaseServiceProviders();
$this->registerCoreContainerAliases();
}
没错在 Application 类的组织函数一共完成 3 个操纵的处置惩罚功用:
经由过程 registerBaseBindings() 要领将「App 实例(即 Laravel 效劳容器)」自身注册到「Laravel 效劳容器」;
经由过程 registerBaseServiceProviders() 注册运用 Laravel 框架的基本效劳提供者;
经由过程 registerCoreContainerAliases() 将细致的「依靠注入容器」及其别号注册到「Laravel 效劳容器」。
这里所说的「注册」归根到底照样在实行「Laravel 效劳容器」的「绑定(bind)」操纵,完成绑定接口到完成。
为了表名我所言非虚,让我们看看 registerBaseBindings() 要领:
/**
* Register the basic bindings into the container. 注册 App 实例自身到 App 容器
*
* @return void
*/
protected function registerBaseBindings()
{
static::setInstance($this);
$this->instance('app', $this);
$this->instance(Container::class, $this);
$this->instance(PackageManifest::class, new PackageManifest(
new Filesystem, $this->basePath(), $this->getCachedPackagesPath()
));
}
我们晓得 instance() 要领会将对象实例 $this 绑定到容器的 app 和 Container::class 接口。后续无论是经由过程 app()->make(‘app’) 照样 app()->make(Container::class) 获取到的完成类都是 $this(即 Laravel 效劳容器实例) 对象。有关 instance 的使用要领能够查阅 Laravel 效劳容器剖析文档,不过我也会在下文中给出相干使用说明。
到这里置信人人对「Laravel 效劳容器」有了一个比较清楚的理解了。
更多Laravel相干技术文章,请接见Laravel框架入门教程栏目举行进修!
以上就是laravel容器是什么的细致内容,更多请关注ki4网别的相干文章!
为木唯品 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:【PHP开发框架】laravel容器是什么