溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Laravel運(yùn)行原理是什么

發(fā)布時間:2020-12-24 09:47:40 來源:億速云 閱讀:161 作者:小新 欄目:編程語言

小編給大家分享一下Laravel運(yùn)行原理是什么,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

運(yùn)行原理概述

Laravel 框架的入口文件 index.php

1、引入自動加載 autoload.php 文件

2、創(chuàng)建應(yīng)用實(shí)例,并同時完成了

基本綁定($this、容器類Container等等)、

基本服務(wù)提供者的注冊(Event、log、routing)、

核心類別名的注冊(比如db、auth、config、router等)

3、開始 Http 請求的處理

make 方法從容器中解析指定的值為實(shí)際的類,比如 $app->make(Illuminate\Contracts\Http\Kernel::class); 解析出來 App\Http\Kernel 

handle 方法對 http 請求進(jìn)行處理

實(shí)際上是 handle 中 sendRequestThroughRouter 處理 http 的請求

首先,將 request 綁定到共享實(shí)例

然后執(zhí)行 bootstarp 方法,運(yùn)行給定的引導(dǎo)類數(shù)組 $bootstrappers,這里是重點(diǎn),包括了加載配置文件、環(huán)境變量、服務(wù)提供者、門面、異常處理、引導(dǎo)提供者等

之后,進(jìn)入管道模式,經(jīng)過中間件的處理過濾后,再進(jìn)行用戶請求的分發(fā)

在請求分發(fā)時,首先,查找與給定請求匹配的路由,然后執(zhí)行 runRoute 方法,實(shí)際處理請求的時候 runRoute 中的 runRouteWithinStack 

最后,經(jīng)過 runRouteWithinStack 中的 run 方法,將請求分配到實(shí)際的控制器中,執(zhí)行閉包或者方法,并得到響應(yīng)結(jié)果

4、 將處理結(jié)果返回

詳細(xì)源碼分析

1、注冊自動加載類,實(shí)現(xiàn)文件的自動加載

require __DIR__.'/../vendor/autoload.php';

2、創(chuàng)建應(yīng)用容器實(shí)例 Application (該實(shí)例繼承自容器類 Container),并綁定核心(web、命令行、異常),方便在需要的時候解析它們

$app = require_once __DIR__.'/../bootstrap/app.php';

app.php 文件如下:

<?php
// 創(chuàng)建Laravel實(shí)例 【3】
$app = new Illuminate\Foundation\Application(
 $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
// 綁定Web端kernel
$app->singleton(
 Illuminate\Contracts\Http\Kernel::class, App\Http\Kernel::class);
// 綁定命令行kernel
$app->singleton(
 Illuminate\Contracts\Console\Kernel::class, App\Console\Kernel::class);
// 綁定異常處理
$app->singleton(
 Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\Handler::class);
// 返回應(yīng)用實(shí)例
return $app;

3、在創(chuàng)建應(yīng)用實(shí)例(Application.php)的構(gòu)造函數(shù)中,將基本綁定注冊到容器中,并注冊了所有的基本服務(wù)提供者,以及在容器中注冊核心類別名

3.1、將基本綁定注冊到容器中

    /**
     * Register the basic bindings into the container.
     *
     * @return void
     */
    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()
        ));
        # 注:instance方法為將...注冊為共享實(shí)例,singleton方法為將...注冊為共享綁定
    }

3.2、注冊所有基本服務(wù)提供者(事件,日志,路由)

protected function registerBaseServiceProviders()
    {
        $this->register(new EventServiceProvider($this));
        $this->register(new LogServiceProvider($this));
        $this->register(new RoutingServiceProvider($this));
    }

3.3、在容器中注冊核心類別名

Laravel運(yùn)行原理是什么

4、上面完成了類的自動加載、服務(wù)提供者注冊、核心類的綁定、以及基本注冊的綁定

5、開始解析 http 的請求

index.php
//5.1
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
//5.2
$response = $kernel->handle(
 $request = Illuminate\Http\Request::capture());

5.1、make方法是從容器解析給定值

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

中的Illuminate\Contracts\Http\Kernel::class 是在index.php 中的$app = require_once __DIR__.'/../bootstrap/app.php';這里面進(jìn)行綁定的,實(shí)際指向的就是App\Http\Kernel::class這個類

5.2、這里對 http 請求進(jìn)行處理

$response = $kernel->handle(
 $request = Illuminate\Http\Request::capture());

進(jìn)入 $kernel 所代表的類 App\Http\Kernel.php 中,我們可以看到其實(shí)里面只是定義了一些中間件相關(guān)的內(nèi)容,并沒有 handle 方法

我們再到它的父類 use Illuminate\Foundation\Http\Kernel as HttpKernel; 中找 handle 方法,可以看到 handle 方法是這樣的

public function handle($request){
    try {
        $request->enableHttpMethodParameterOverride();
        // 最核心的處理http請求的地方【6】
        $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;}

6、處理 Http 請求(將 request 綁定到共享實(shí)例,并使用管道模式處理用戶請求)

vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php的handle方法// 最核心的處理http請求的地方$response = $this->sendRequestThroughRouter($request);protected function sendRequestThroughRouter($request){
    // 將請求$request綁定到共享實(shí)例
    $this->app->instance('request', $request);
    // 將請求request從已解析的門面實(shí)例中清除(因?yàn)橐呀?jīng)綁定到共享實(shí)例中了,沒必要再浪費(fèi)資源了)
    Facade::clearResolvedInstance('request');
    // 引導(dǎo)應(yīng)用程序進(jìn)行HTTP請求
    $this->bootstrap();【7、8】    // 進(jìn)入管道模式,經(jīng)過中間件,然后處理用戶的請求【9、10】
    return (new Pipeline($this->app))
                ->send($request)
                ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
                ->then($this->dispatchToRouter());}

7、在 bootstrap 方法中,運(yùn)行給定的 引導(dǎo)類數(shù)組 $bootstrappers,加載配置文件、環(huán)境變量、服務(wù)提供者、門面、異常處理、引導(dǎo)提供者,非常重要的一步,位置在 vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php

/**
 * Bootstrap the application for HTTP requests.
 *
 * @return void
 */public function bootstrap(){
    if (! $this->app->hasBeenBootstrapped()) {
        $this->app->bootstrapWith($this->bootstrappers());
    }}
/**
 * 運(yùn)行給定的引導(dǎo)類數(shù)組
 *
 * @param  string[]  $bootstrappers
 * @return void
 */public function bootstrapWith(array $bootstrappers){
    $this->hasBeenBootstrapped = true;
    foreach ($bootstrappers as $bootstrapper) {
        $this['events']->dispatch('bootstrapping: '.$bootstrapper, [$this]);
        $this->make($bootstrapper)->bootstrap($this);
        $this['events']->dispatch('bootstrapped: '.$bootstrapper, [$this]);
    }}/**
 * Get the bootstrap classes for the application.
 *
 * @return array
 */protected function bootstrappers(){
    return $this->bootstrappers;}/**
 * 應(yīng)用程序的引導(dǎo)類
 *
 * @var array
 */protected $bootstrappers = [
    // 加載環(huán)境變量
    \Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class,
    // 加載config配置文件【重點(diǎn)】
    \Illuminate\Foundation\Bootstrap\LoadConfiguration::class,
    // 加載異常處理
    \Illuminate\Foundation\Bootstrap\HandleExceptions::class,
    // 加載門面注冊
    \Illuminate\Foundation\Bootstrap\RegisterFacades::class,
    // 加載在config/app.php中的providers數(shù)組里所定義的服務(wù)【8 重點(diǎn)】
    \Illuminate\Foundation\Bootstrap\RegisterProviders::class,
    // 記載引導(dǎo)提供者
    \Illuminate\Foundation\Bootstrap\BootProviders::class,];

8、加載 config/app.php 中的 providers 數(shù)組里定義的服務(wù)

Illuminate\Auth\AuthServiceProvider::class,Illuminate\Broadcasting\BroadcastServiceProvider::class,....../**
 * 自己添加的服務(wù)提供者 */\App\Providers\HelperServiceProvider::class,

可以看到,關(guān)于常用的 Redis、session、queue、auth、database、Route 等服務(wù)都是在這里進(jìn)行加載的

9、使用管道模式處理用戶請求,先經(jīng)過中間件進(jìn)行處理和過濾

return (new Pipeline($this->app))
    ->send($request)
    // 如果沒有為程序禁用中間件,則加載中間件(位置在app/Http/Kernel.php的$middleware屬性)
    ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
    ->then($this->dispatchToRouter());}

app/Http/Kernel.php

/**
 * 應(yīng)用程序的全局HTTP中間件
 *
 * These middleware are run during every request to your application.
 *
 * @var array
 */protected $middleware = [
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,];

10、經(jīng)過中間件處理后,再進(jìn)行請求分發(fā)(包括查找匹配路由)

/**
 * 10.1 通過中間件/路由器發(fā)送給定的請求
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
 protected function sendRequestThroughRouter($request){
    ...
    return (new Pipeline($this->app))
        ...
        // 進(jìn)行請求分發(fā)
        ->then($this->dispatchToRouter());}
/**
 * 10.2 獲取路由調(diào)度程序回調(diào)
 *
 * @return \Closure
 */protected function dispatchToRouter(){
    return function ($request) {
        $this->app->instance('request', $request);
        // 將請求發(fā)送到應(yīng)用程序
        return $this->router->dispatch($request);
    };}
/**
 * 10.3 將請求發(fā)送到應(yīng)用程序
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
 */
 public function dispatch(Request $request){
    $this->currentRequest = $request;
    return $this->dispatchToRoute($request);}
 /**
 * 10.4 將請求分派到路由并返回響應(yīng)【重點(diǎn)在runRoute方法】
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
 */public function dispatchToRoute(Request $request){   
    return $this->runRoute($request, $this->findRoute($request));}
/**
 * 10.5 查找與給定請求匹配的路由
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Routing\Route
 */protected function findRoute($request){
    $this->current = $route = $this->routes->match($request);
    $this->container->instance(Route::class, $route);
    return $route;}
/**
 * 10.6 查找與給定請求匹配的第一條路由
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Routing\Route
 *
 * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
 */public function match(Request $request){
    // 獲取用戶的請求類型(get、post、delete、put),然后根據(jù)請求類型選擇對應(yīng)的路由
    $routes = $this->get($request->getMethod());
    // 匹配路由
    $route = $this->matchAgainstRoutes($routes, $request);
    if (! is_null($route)) {
        return $route->bind($request);
    }
    $others = $this->checkForAlternateVerbs($request);
    if (count($others) > 0) {
        return $this->getRouteForMethods($request, $others);
    }
    throw new NotFoundHttpException;}

到現(xiàn)在,已經(jīng)找到與請求相匹配的路由了,之后將運(yùn)行了,也就是 10.4 中的 runRoute 方法

/**
 * 10.7 返回給定路線的響應(yīng)
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Routing\Route  $route
 * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
 */protected function runRoute(Request $request, Route $route){
    $request->setRouteResolver(function () use ($route) {
        return $route;
    });
    $this->events->dispatch(new Events\RouteMatched($route, $request));
    return $this->prepareResponse($request,
        $this->runRouteWithinStack($route, $request)
    );}
/**
 * Run the given route within a Stack "onion" instance.
 * 10.8 在棧中運(yùn)行路由,先檢查有沒有控制器中間件,如果有先運(yùn)行控制器中間件
 *
 * @param  \Illuminate\Routing\Route  $route
 * @param  \Illuminate\Http\Request  $request
 * @return mixed
 */protected function runRouteWithinStack(Route $route, Request $request){
    $shouldSkipMiddleware = $this->container->bound('middleware.disable') &&
                            $this->container->make('middleware.disable') === true;
    $middleware = $shouldSkipMiddleware ? [] : $this->gatherRouteMiddleware($route);
    return (new Pipeline($this->container))
        ->send($request)
        ->through($middleware)
        ->then(function ($request) use ($route) {
            return $this->prepareResponse(
                $request, $route->run()
            );
        });}
 /**
     * Run the route action and return the response.
     * 10.9 最后一步,運(yùn)行控制器的方法,處理數(shù)據(jù)
     * @return mixed
     */
    public function run()
    {
        $this->container = $this->container ?: new Container;

        try {
            if ($this->isControllerAction()) {
                return $this->runController();
            }

            return $this->runCallable();
        } catch (HttpResponseException $e) {
            return $e->getResponse();
        }
    }

11、運(yùn)行路由并返回響應(yīng)(重點(diǎn))
可以看到,10.7 中有一個方法是 prepareResponse,該方法是從給定值創(chuàng)建響應(yīng)實(shí)例,而 runRouteWithinStack 方法則是在棧中運(yùn)行路由,也就是說,http 的請求和響應(yīng)都將在這里完成。

看完了這篇文章,相信你對“Laravel運(yùn)行原理是什么”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI