laravel大致的運行過程,先記錄一下。 當然我是在看到了 這個博文https://my.oschina.net/falcon10086/blog/647507,寫的很棒。
laravel唯一的路口文件 /public/index.php 一步一步來看
require __DIR__.'/../bootstrap/autoload.php';引入類加載器,查看autoload.php文件
define('LARAVEL_START', microtime(true));require __DIR__.'/../vendor/autoload.php';$compiledPath = __DIR__.'/cache/compiled.php';if (file_exists($compiledPath)) { require $compiledPath;}第一行代碼定義程序運行的開始事件; 第二段代碼請求了vendor/autoload.php文件,也就是說使用了composer自帶的類加載器。 第三段和第四段代碼用來優化效率。
現在繼續看index.php文件
$app = require_once __DIR__.'/../bootstrap/app.php';查看bootstrap/app.php文件
$app = new Illuminate/Foundation/application( realpath(__DIR__.'/../'));$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;先創建了一個 Illuminate/Foundation/Application 實例,該類繼承Illuminate/Container/Container,調用其singleton()方法綁定接口和類,最后返回實例,這里是一個單例。
看一下 Illuminate/Foundation/Application 構造函數
public function __construct($basePath = null) { $this->registerBaseBindings(); $this->registerBaseServicePRoviders(); $this->registerCoreContainerAliases(); if ($basePath) { $this->setBasePath($basePath); } }$this->registerBaseBindings()方法
protected function registerBaseBindings() { /* * 首先需要明白當前類繼承自 Illuminate/Container/Container * * setInstance 是 Illuminate/Container/Container 中的方法將類和當前對象綁定, 當然這樣說是為了跟容易表示,下面的注釋也是如此 */ static::setInstance($this); /* * 將'app'和當前對象放在 Illuminate/Container/Container 的 instances 數組中, * 形成一個映射,當然當前類繼承自 Illuminate/Container/Container 也就是調用自己的 instance() 方法 * 這樣'app'指向了當前對象,實現綁定。 */ $this->instance('app', $this); /* * 和上面的類似,綁定 */ $this->instance('Illuminate/Container/Container', $this); }$this->registerBaseServiceProviders()
protected function registerBaseServiceProviders() { /* * 依賴注入: 當前對象被注入到 EventServiceProvider、RoutingServiceProvider 中 */ $this->register(new EventServiceProvider($this)); $this->register(new RoutingServiceProvider($this)); }注冊服務提供器。
$this->registerCoreContainerAliases()
public function registerCoreContainerAliases() { $aliases = [ 'app' => ['Illuminate/Foundation/Application', 'Illuminate/Contracts/Container/Container', 'Illuminate/Contracts/Foundation/Application'] ... ]; foreach ($aliases as $key => $aliases) { foreach ((array) $aliases as $alias) { $this->alias($key, $alias); } } }注冊核心類的別名,簡化命名; aliases 數組中一個復雜的名字對應別名。 例如下面的: Illuminate/Foundation/Application => app; Illuminate/Contracts/Container/Container => app; foreach 就是具體的綁定。
現在分析app.php中的$app->singleton()。該方法將接口和具體實現類綁定在一起,之后用到接口的時候會調用對應的具體實現。該部分源碼比較復雜,可以自己看一下,主要部分是 Illuminate/Container/Container 的 make 和 build 方法。
現在再次回到index.php
$kernel = $app->make(Illuminate/Contracts/Http/Kernel::class);由于 bootstrap/app.php 中綁定了接口和具體實現,這里調用 make 就會創建App/Http/Kernel::class 類實例。
最后kernel 處理 http 請求,接收請求, 發送響應, 終止程序,處理一些收尾的工作。
新聞熱點
疑難解答