這篇文章帶給大家的內容是關於Laravel中HTTP核心的詳細解析,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
Http Kernel
Http Kernel是Laravel中用來串聯框架的各個核心元件來網路請求的,簡單的說只要是透過public/index .php
來啟動框架的都會用到Http Kernel,而另外的類似通過artisan
命令、計劃任務、隊列啟動框架進行處理的都會用到Console Kernel, 今天我們先梳理一下Http Kernel所做的事情。
既然Http Kernel是Laravel中用來串聯框架的各個部分處理網路請求的,我們來看一下核心是怎麼載入到Laravel應用實例中來的,在public/index.php中我們就會看見首先就會透過bootstrap/app.php這個腳手架檔案來初始化應用程式:
下面是 bootstrap/app.php 的程式碼,包含兩個主要部分創建應用實例和綁定內核至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;
HTTP 內核繼承自IlluminateFoundationHttpKernel類,在HTTP 內核中內它定義了中間件相關數組, 中間件提供了一個方便的機制來過濾進入應用的HTTP 請求和加工流出應用的HTTP回應。
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, \App\Http\Middleware\TrustProxies::class, ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; /** * The application's route middleware. * * These middleware may be assigned to groups or used inpidually. * * @var array */ protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ]; }
在其父類別「IlluminateFoundationHttpKernel」 內部定義了屬性名稱為「bootstrappers」 的引導程式陣列:
protected $bootstrappers = [ \Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class, \Illuminate\Foundation\Bootstrap\LoadConfiguration::class, \Illuminate\Foundation\Bootstrap\HandleExceptions::class, \Illuminate\Foundation\Bootstrap\RegisterFacades::class, \Illuminate\Foundation\Bootstrap\RegisterProviders::class, \Illuminate\Foundation\Bootstrap\BootProviders::class, ];
#引導程式群組中包含完成環境偵測、設定載入、異常處理、 Facades 註冊、服務提供者註冊、啟動服務這六個引導程式。
在將應用程式初始化階段將Http核心綁定至應用程式的服務容器後,緊接著在public/index.php中我們可以看到使用了服務容器的make方法將Http核心實例解析了出來:
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
在實例化核心時,將在HTTP 核心中定義的中間件註冊到了路由器,註冊後就可以在實際處理HTTP 請求前呼叫路由上應用的中間件實現過濾請求的目的:
namespace Illuminate\Foundation\Http; ... class Kernel implements KernelContract { /** * Create a new HTTP kernel instance. * * @param \Illuminate\Contracts\Foundation\Application $app * @param \Illuminate\Routing\Router $router * @return void */ public function __construct(Application $app, Router $router) { $this->app = $app; $this->router = $router; $router->middlewarePriority = $this->middlewarePriority; foreach ($this->middlewareGroups as $key => $middleware) { $router->middlewareGroup($key, $middleware); } foreach ($this->routeMiddleware as $key => $middleware) { $router->aliasMiddleware($key, $middleware); } } } namespace Illuminate/Routing; class Router implements RegistrarContract, BindingRegistrar { /** * Register a group of middleware. * * @param string $name * @param array $middleware * @return $this */ public function middlewareGroup($name, array $middleware) { $this->middlewareGroups[$name] = $middleware; return $this; } /** * Register a short-hand name for a middleware. * * @param string $name * @param string $class * @return $this */ public function aliasMiddleware($name, $class) { $this->middleware[$name] = $class; return $this; } }
透過服務解析完成Http核心實例的建立後就可以用HTTP核心實例來處理HTTP請求了
//public/index.php $response = $kernel->handle( $request = Illuminate\Http\Request::capture() );
在處理請求之前會先透過Illuminate\Http\Request的 capture() 方法以進入應用的HTTP請求的資訊為基礎建立出一個Laravel Request請求實例,在後續應用剩餘的生命週期中Request請求實例就是對本次HTTP請求的抽象
將HTTP請求抽象化成Laravel Request請求實例後,請求實例會被傳導進入到HTTP核心的handle方法內部,請求的處理就是由handle方法來完成的。
namespace Illuminate\Foundation\Http; class Kernel implements KernelContract { /** * Handle an incoming HTTP request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function handle($request) { try { $request->enableHttpMethodParameterOverride(); $response = $this->sendRequestThroughRouter($request); } catch (Exception $e) { $this->reportException($e); $response = $this->renderException($request, $e); } catch (Throwable $e) { $this->reportException($e = new FatalThrowableError($e)); $response = $this->renderException($request, $e); } $this->app['events']->dispatch( new Events\RequestHandled($request, $response) ); return $response; } }
handle 方法接收一個請求對象,最後產生一個回應對象。其實handle方法我們已經很熟悉了在講解很多模組的時候都是以它為出發點逐步深入到模組的內部去講解模組內的邏輯的,其中sendRequestThroughRouter方法在服務提供者和中間件都提到過,它會載入在核心中定義的引導程式來引導啟動應用程式然後會將使用Pipeline物件傳輸HTTP請求物件流經框架中定義的HTTP中間件們和路由中間件們來完成過濾請求最終將請求傳遞給處理程序(控制器方法或路由中的閉包)由處理程序傳回對應的回應。
protected function sendRequestThroughRouter($request) { $this->app->instance('request', $request); Facade::clearResolvedInstance('request'); $this->bootstrap(); return (new Pipeline($this->app)) ->send($request) ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware) ->then($this->dispatchToRouter()); } /*引导启动Laravel应用程序 1. DetectEnvironment 检查环境 2. LoadConfiguration 加载应用配置 3. ConfigureLogging 配置日至 4. HandleException 注册异常处理的Handler 5. RegisterFacades 注册Facades 6. RegisterProviders 注册Providers 7. BootProviders 启动Providers */ public function bootstrap() { if (! $this->app->hasBeenBootstrapped()) { /**依次执行$bootstrappers中每一个bootstrapper的bootstrap()函数 $bootstrappers = [ 'Illuminate\Foundation\Bootstrap\DetectEnvironment', 'Illuminate\Foundation\Bootstrap\LoadConfiguration', 'Illuminate\Foundation\Bootstrap\ConfigureLogging', 'Illuminate\Foundation\Bootstrap\HandleExceptions', 'Illuminate\Foundation\Bootstrap\RegisterFacades', 'Illuminate\Foundation\Bootstrap\RegisterProviders', 'Illuminate\Foundation\Bootstrap\BootProviders', ];*/ $this->app->bootstrapWith($this->bootstrappers()); } }
經過上面的幾個階段後我們最終拿到了要回傳的回應,接下來就是發送回應了。
//public/index.php $response = $kernel->handle( $request = Illuminate\Http\Request::capture() ); // 发送响应 $response->send();
發送回應由Illuminate\Http\Response
的send()
方法完成父類別其定義在父類別Symfony\Component\HttpFoundation\Response
中。
public function send() { $this->sendHeaders();// 发送响应头部信息 $this->sendContent();// 发送报文主题 if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } elseif (!\in_array(PHP_SAPI, array('cli', 'phpdbg'), true)) { static::closeOutputBuffers(0, true); } return $this; }
關於Response物件的詳細分析可以參考我們之前講解Laravel Response物件的章節。
回應傳送後,HTTP核心會呼叫terminable
中間件做一些後續的處理工作。例如,Laravel 內建的「session」中間件會在回應傳送到瀏覽器之後將會話資料寫入記憶體中。
// public/index.php // 终止程序 $kernel->terminate($request, $response);
//Illuminate\Foundation\Http\Kernel public function terminate($request, $response) { $this->terminateMiddleware($request, $response); $this->app->terminate(); } // 终止中间件 protected function terminateMiddleware($request, $response) { $middlewares = $this->app->shouldSkipMiddleware() ? [] : array_merge( $this->gatherRouteMiddleware($request), $this->middleware ); foreach ($middlewares as $middleware) { if (! is_string($middleware)) { continue; } list($name, $parameters) = $this->parseMiddleware($middleware); $instance = $this->app->make($name); if (method_exists($instance, 'terminate')) { $instance->terminate($request, $response); } } }
Http核心的terminate
方法會呼叫teminable
中間件的terminate
方法,呼叫完成後從HTTP請求進來到回傳回應整個應用程式的生命週期就結束了。
本節介紹的HTTP核心起到的主要是串聯作用,其中設計到的初始化應用、引導應用、將HTTP請求抽象化成Request物件、傳遞Request物件通過中間件到達處理程序產生回應以及回應傳送給客戶端。
以上是Laravel中HTTP內核的詳細解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!