通過(guò)閱讀Laravel源碼碧绞,配合官方文檔介紹,了解Laravel框架的運(yùn)行流程吱窝。本章介紹啟動(dòng)應(yīng)用程序的時(shí)候讥邻,初始化服務(wù)容器過(guò)程中,執(zhí)行的一系列基礎(chǔ)內(nèi)容和服務(wù)的注冊(cè)院峡,綁定兴使。最后生成一個(gè)服務(wù)容器
啟動(dòng)應(yīng)用程序介紹
Laravel應(yīng)用的所有請(qǐng)求入口是public/index.php文件,首先看該文件中的代碼以及簡(jiǎn)單介紹
文件:bootstrap/app.php
<?php
define('LARAVEL_START', microtime(true));
// 載入Composer生成的自動(dòng)加載文件
require __DIR__.'/../vendor/autoload.php';
// 啟動(dòng)應(yīng)用照激,完成服務(wù)容器的實(shí)例化和基本注冊(cè)
$app = require_once __DIR__.'/../bootstrap/app.php';
// 處理請(qǐng)求并返回響應(yīng)結(jié)果
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
入口文件中的代碼发魄,簡(jiǎn)單清晰的展示了請(qǐng)求到響應(yīng)的整個(gè)生命周期的過(guò)程,首先是加載Composer的自動(dòng)加載文件俩垃,然后實(shí)例化服務(wù)容器励幼,并注冊(cè)核心服務(wù)。然后通過(guò)kernel內(nèi)核處理請(qǐng)求并返回響應(yīng)結(jié)果口柳。
服務(wù)容器實(shí)例化過(guò)程
啟動(dòng)Laravel應(yīng)用程序的入口文件中苹粟,通過(guò)$app = require_once __DIR__.'/../bootstrap/app.php';
獲取服務(wù)容器對(duì)象,查看實(shí)例化服務(wù)容器過(guò)程中的詳細(xì)代碼片段跃闹,然后再逐步了解每一步的意圖
文件: bootstrap/app.php
<?php
// 服務(wù)容器的實(shí)例化
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
// 綁定 接口和對(duì)應(yīng)到
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
return $app;
這段代碼中嵌削,首先是實(shí)例化Illuminate\Foundation\Application類(lèi),得到一個(gè)對(duì)象望艺,即服務(wù)容器對(duì)象苛秕。繼續(xù)查看實(shí)例化這個(gè)類(lèi)的過(guò)程中都做了哪些處理。
文件:vendor/laravel/framework/src/Illuminate/Foundation/Application.php
public function __construct($basePath = null)
{
if ($basePath) {
$this->setBasePath($basePath);
}
$this->registerBaseBindings();
$this->registerBaseServiceProviders();
$this->registerCoreContainerAliases();
}
這個(gè)構(gòu)造函數(shù)中荣茫,依次實(shí)現(xiàn)設(shè)置應(yīng)用的基本路徑想帅,注冊(cè)基礎(chǔ)綁定懂拾,注冊(cè)基礎(chǔ)服務(wù)提供者麦备,最后注冊(cè)核心類(lèi)的別名
1. 設(shè)置基本路徑
if ($basePath) {
$this->setBasePath($basePath);
}
為應(yīng)用設(shè)置基本路徑
public function setBasePath($basePath)
{
$this->basePath = rtrim($basePath, '\/');
$this->bindPathsInContainer();
return $this;
}
為服務(wù)容器綁定所有項(xiàng)目應(yīng)用的路徑
protected function bindPathsInContainer()
{
$this->instance('path', $this->path());
$this->instance('path.base', $this->basePath());
$this->instance('path.lang', $this->langPath());
$this->instance('path.config', $this->configPath());
$this->instance('path.public', $this->publicPath());
$this->instance('path.storage', $this->storagePath());
$this->instance('path.database', $this->databasePath());
$this->instance('path.resources', $this->resourcePath());
$this->instance('path.bootstrap', $this->bootstrapPath());
}
2. 注冊(cè)基礎(chǔ)綁定到容器
$this->registerBaseBindings();
這段代碼用來(lái)向容器中注冊(cè)綁定基礎(chǔ)服務(wù)。
文件:vendor/laravel/framework/src/Illuminate/Foundation/Application.php
protected function registerBaseBindings()
{
static::setInstance($this);
$this->instance('app', $this);
$this->instance(Container::class, $this);
$this->singleton(Mix::class);
$this->instance(PackageManifest::class, new PackageManifest(
new Filesystem, $this->basePath(), $this->getCachedPackagesPath()
));
}
static::setInstance($this);
設(shè)置當(dāng)前容器對(duì)象為當(dāng)前的全局容器抄瑟,后續(xù)代碼中咧欣,可以通過(guò)
文件:vendor/laravel/framework/src/Illuminate/Container/Container.php中的靜態(tài)方法getInstance()直接獲取服務(wù)容器實(shí)例浅缸。
public static function getInstance()
{
if (is_null(static::$instance)) {
static::$instance = new static;
}
return static::$instance;
}
$this->instance('app', $this);
,$this->instance(Container::class, $this);
向服務(wù)容器的共享實(shí)例數(shù)組(instances)中注冊(cè)兩個(gè)單例服務(wù)。在后續(xù)的使用中魄咕,可以通過(guò)此處綁定的別名找到對(duì)應(yīng)的服務(wù)容器實(shí)例衩椒。
同理,代碼$this->instance(PackageManifest::class, new PackageManifest( new Filesystem, $this->basePath(), $this->getCachedPackagesPath() ));
也向instances數(shù)組中,綁定一個(gè)文件系統(tǒng)單例服務(wù)毛萌。
instance方法的實(shí)現(xiàn)內(nèi)容:
文件:vendor/laravel/framework/src/Illuminate/Container/Container.php
public function instance($abstract, $instance)
{
$this->removeAbstractAlias($abstract);
$isBound = $this->bound($abstract);
unset($this->aliases[$abstract]);
$this->instances[$abstract] = $instance;
if ($isBound) {
$this->rebound($abstract);
}
return $instance;
}
$this->removeAbstractAlias($abstract);
從上下文綁定別名緩存中刪除該別名
protected function removeAbstractAlias($searched)
{
// 這個(gè)$this->aliases數(shù)組存放的是已注冊(cè)的類(lèi)名的別名
if (! isset($this->aliases[$searched])) {
return;
}
foreach ($this->abstractAliases as $abstract => $aliases) {
foreach ($aliases as $index => $alias) {
if ($alias == $searched) {
unset($this->abstractAliases[$abstract][$index]);
}
}
}
}
$isBound = $this->bound($abstract);
判斷是否已綁定給定的抽象類(lèi)型苟弛。
$this->instances[$abstract] = $instance;
將傳進(jìn)來(lái)的instance對(duì)象和abstract接口注冊(cè)到容器中到共享實(shí)例數(shù)組($instances)中
3. 注冊(cè)基礎(chǔ)服務(wù)提供者
$this->registerBaseServiceProviders();
這行代碼實(shí)現(xiàn)向服務(wù)容器注冊(cè)最基礎(chǔ)的服務(wù)提供者。分別為事件服務(wù)阁将,日志服務(wù)和路由服務(wù)
文件:vendor/laravel/framework/src/Illuminate/Foundation/Application.php
protected function registerBaseServiceProviders()
{
$this->register(new EventServiceProvider($this));
$this->register(new LogServiceProvider($this));
$this->register(new RoutingServiceProvider($this));
}
向服務(wù)容器提供這些基礎(chǔ)服務(wù)膏秫,首先實(shí)例化服務(wù)提供者,然后通過(guò)容器中的register方法完成注冊(cè)做盅。注冊(cè)過(guò)程:
文件:vendor/laravel/framework/src/Illuminate/Foundation/Application.php
public function register($provider, $force = false)
{
if (($registered = $this->getProvider($provider)) && ! $force) {
return $registered;
}
if (is_string($provider)) {
$provider = $this->resolveProvider($provider);
}
$provider->register();
if (property_exists($provider, 'bindings')) {
foreach ($provider->bindings as $key => $value) {
$this->bind($key, $value);
}
}
if (property_exists($provider, 'singletons')) {
foreach ($provider->singletons as $key => $value) {
$this->singleton($key, $value);
}
}
$this->markAsRegistered($provider);
if ($this->booted) {
$this->bootProvider($provider);
}
return $provider;
}
首先缤削,判斷該服務(wù)提供者是否已經(jīng)被注冊(cè)過(guò),并且$force = false
吹榴,則直接返回注冊(cè)結(jié)果
然后亭敢,判斷傳進(jìn)來(lái)的provider是否為字符串,如果是图筹,應(yīng)該是一個(gè)類(lèi)名的字符串帅刀,則實(shí)例化該服務(wù)提供者。
拿到未被注冊(cè)過(guò)的服務(wù)提供者的對(duì)象之后名远剩,調(diào)用該對(duì)象的register方法
每個(gè)服務(wù)提供者都會(huì)繼承Illuminate\Support\ServiceProvider劝篷。在該類(lèi)中有一個(gè)register方法,然后每個(gè)服務(wù)提供者都會(huì)各自實(shí)現(xiàn)這個(gè)register方法民宿,用來(lái)提供自己的服務(wù)。
$this->markAsRegistered($provider);
標(biāo)示該服務(wù)器提供者已經(jīng)完成注冊(cè)像鸡。在該方法中會(huì)將完成注冊(cè)的服務(wù)提供者的對(duì)象存入serviceProviders數(shù)組中活鹰,然后將該服務(wù)器提供者的類(lèi)名作為key,value設(shè)置為true的鍵值對(duì)的形式只估,存儲(chǔ)loadedProviders數(shù)組中志群。
4. 注冊(cè)核心類(lèi)別名
public function registerCoreContainerAliases()
{
foreach ([
'app' => [self::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class, \Psr\Container\ContainerInterface::class],
'auth' => [\Illuminate\Auth\AuthManager::class, \Illuminate\Contracts\Auth\Factory::class],
'auth.driver' => [\Illuminate\Contracts\Auth\Guard::class],
'blade.compiler' => [\Illuminate\View\Compilers\BladeCompiler::class],
'cache' => [\Illuminate\Cache\CacheManager::class, \Illuminate\Contracts\Cache\Factory::class],
'cache.store' => [\Illuminate\Cache\Repository::class, \Illuminate\Contracts\Cache\Repository::class],
'config' => [\Illuminate\Config\Repository::class, \Illuminate\Contracts\Config\Repository::class],
'cookie' => [\Illuminate\Cookie\CookieJar::class, \Illuminate\Contracts\Cookie\Factory::class, \Illuminate\Contracts\Cookie\QueueingFactory::class],
'encrypter' => [\Illuminate\Encryption\Encrypter::class, \Illuminate\Contracts\Encryption\Encrypter::class],
'db' => [\Illuminate\Database\DatabaseManager::class],
'db.connection' => [\Illuminate\Database\Connection::class, \Illuminate\Database\ConnectionInterface::class],
'events' => [\Illuminate\Events\Dispatcher::class, \Illuminate\Contracts\Events\Dispatcher::class],
'files' => [\Illuminate\Filesystem\Filesystem::class],
'filesystem' => [\Illuminate\Filesystem\FilesystemManager::class, \Illuminate\Contracts\Filesystem\Factory::class],
'filesystem.disk' => [\Illuminate\Contracts\Filesystem\Filesystem::class],
'filesystem.cloud' => [\Illuminate\Contracts\Filesystem\Cloud::class],
'hash' => [\Illuminate\Hashing\HashManager::class],
'hash.driver' => [\Illuminate\Contracts\Hashing\Hasher::class],
'translator' => [\Illuminate\Translation\Translator::class, \Illuminate\Contracts\Translation\Translator::class],
'log' => [\Illuminate\Log\LogManager::class, \Psr\Log\LoggerInterface::class],
'mailer' => [\Illuminate\Mail\Mailer::class, \Illuminate\Contracts\Mail\Mailer::class, \Illuminate\Contracts\Mail\MailQueue::class],
'auth.password' => [\Illuminate\Auth\Passwords\PasswordBrokerManager::class, \Illuminate\Contracts\Auth\PasswordBrokerFactory::class],
'auth.password.broker' => [\Illuminate\Auth\Passwords\PasswordBroker::class, \Illuminate\Contracts\Auth\PasswordBroker::class],
'queue' => [\Illuminate\Queue\QueueManager::class, \Illuminate\Contracts\Queue\Factory::class, \Illuminate\Contracts\Queue\Monitor::class],
'queue.connection' => [\Illuminate\Contracts\Queue\Queue::class],
'queue.failer' => [\Illuminate\Queue\Failed\FailedJobProviderInterface::class],
'redirect' => [\Illuminate\Routing\Redirector::class],
'redis' => [\Illuminate\Redis\RedisManager::class, \Illuminate\Contracts\Redis\Factory::class],
'request' => [\Illuminate\Http\Request::class, \Symfony\Component\HttpFoundation\Request::class],
'router' => [\Illuminate\Routing\Router::class, \Illuminate\Contracts\Routing\Registrar::class, \Illuminate\Contracts\Routing\BindingRegistrar::class],
'session' => [\Illuminate\Session\SessionManager::class],
'session.store' => [\Illuminate\Session\Store::class, \Illuminate\Contracts\Session\Session::class],
'url' => [\Illuminate\Routing\UrlGenerator::class, \Illuminate\Contracts\Routing\UrlGenerator::class],
'validator' => [\Illuminate\Validation\Factory::class, \Illuminate\Contracts\Validation\Factory::class],
'view' => [\Illuminate\View\Factory::class, \Illuminate\Contracts\View\Factory::class],
] as $key => $aliases) {
foreach ($aliases as $alias) {
$this->alias($key, $alias);
}
}
}
這段代碼主要是將這個(gè)框架用到的核心服務(wù)設(shè)置一個(gè)別名,在服務(wù)解析過(guò)過(guò)程中蛔钙,需要根據(jù)類(lèi)名或者接口名找到服務(wù)別名锌云,然后通過(guò)服務(wù)別名獲取具體的服務(wù)。
向服務(wù)容器綁定一些重要接口
文件:bootstrap/app.php
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
這里$app
就是服務(wù)容器對(duì)象吁脱,調(diào)用其singleton()方法是向服務(wù)容器中注冊(cè)一個(gè)共享綁定桑涎。這個(gè)方法接收的第一個(gè)參數(shù)作為服務(wù)名的接口,第二個(gè)參數(shù)作為提供服務(wù)的類(lèi)兼贡,在方法內(nèi)部會(huì)通過(guò)反射機(jī)制攻冷,將其實(shí)例化之后。存入容器遍希。
文件:vendor/laravel/framework/src/Illuminate/Container/Container.php
public function singleton($abstract, $concrete = null)
{
$this->bind($abstract, $concrete, true);
}
這個(gè)方法內(nèi)部只是調(diào)用了bind()方法等曼,并且第三個(gè)參數(shù)傳入true,表示作為共享服務(wù)綁定到容器。
public function bind($abstract, $concrete = null, $shared = false)
{
$this->dropStaleInstances($abstract);
if (is_null($concrete)) {
$concrete = $abstract;
}
if (! $concrete instanceof Closure) {
$concrete = $this->getClosure($abstract, $concrete);
}
$this->bindings[$abstract] = compact('concrete', 'shared');
if ($this->resolved($abstract)) {
$this->rebound($abstract);
}
}
這個(gè)方法中禁谦,是將傳進(jìn)來(lái)的接口參數(shù)和提供服務(wù)的回調(diào)函數(shù)綁定到容器的bindings數(shù)組中胁黑。
至此,應(yīng)用程序的準(zhǔn)備工作就已經(jīng)做完了州泊,生成了一個(gè)服務(wù)容器丧蘸,并向容器中注冊(cè)綁定了一些基礎(chǔ)服務(wù),以及綁定了一些重要的接口拥诡。下一篇文章<<Laravel源碼閱讀 - 接收請(qǐng)求并返回結(jié)果>>介紹應(yīng)用接收到http請(qǐng)求并返回結(jié)果的內(nèi)容