目錄
詳細源碼分析" >詳細源碼分析
首頁 php框架 Laravel 一篇文章帶你徹底搞懂Laravel運作原理!

一篇文章帶你徹底搞懂Laravel運作原理!

Dec 23, 2020 am 09:12 AM
laravel

##上中對

Laravel框架##aravel運作原則,希望教學為需要的朋友有所幫助!

前言

知其然知其所以然,剛開始接觸框架的時候大不部分人肯定一臉懵逼,不知道如何實現的,沒有一定的基礎知識,直接去看框架的源碼,只會被直接勸退,Laravel 框架是一款非常優秀的PHP 框架,這篇文章就是帶你徹底搞懂框架的運作原理,好讓你在面試的過程中有些談資(吹牛),學習和研究優秀框架的源碼也有助於我們自身技術的提升,接下來係好安全帶,老司機要開始開車了! ! !

準備知識

  • 熟悉php 基本知識,如常見的陣列方法,閉包函數的使用,魔術方法的使用
  • 熟悉php 的反射機制和依賴注入
  • 熟悉php 命名空間概念和compose 自動載入
  • 熟悉常見的設計模式,包括但不限於單例模式,工廠模式,門面模式,註冊樹模式,裝飾者模式等

運行原理概述

#Laravel 框架的入口檔案index.php

1、引入自動載入autoload.php 檔案

2、建立應用程式實例,並同時完成了

基本绑定($this、容器类Container等等)、

基本服务提供者的注册(Event、log、routing)、

核心类别名的注册(比如db、auth、config、router等)
登入後複製

3、開始Http 請求的處理

make 方法从容器中解析指定的值为实际的类,比如 $app->make(Illuminate\Contracts\Http\Kernel::class); 解析出来 App\Http\Kernel 

handle 方法对 http 请求进行处理

实际上是 handle 中 sendRequestThroughRouter 处理 http 的请求

首先,将 request 绑定到共享实例

然后执行 bootstarp 方法,运行给定的引导类数组 $bootstrappers,这里是重点,包括了加载配置文件、环境变量、服务提供者、门面、异常处理、引导提供者等

之后,进入管道模式,经过中间件的处理过滤后,再进行用户请求的分发

在请求分发时,首先,查找与给定请求匹配的路由,然后执行 runRoute 方法,实际处理请求的时候 runRoute 中的 runRouteWithinStack 

最后,经过 runRouteWithinStack 中的 run 方法,将请求分配到实际的控制器中,执行闭包或者方法,并得到响应结果
登入後複製

4、 將處理結果回傳

1、註冊自動載入類,實現檔案的自動載入

require __DIR__.'/../vendor/autoload.php';
登入後複製

2、建立應用程式容器實例Application (該實例繼承自容器類別Container),並綁定核心(web、命令列、異常),方便在需要的時候解析它們

$app = require_once __DIR__.'/../bootstrap/app.php';
登入後複製

app.php 檔案如下:

<?php
// 创建Laravel实例 【3】
$app = new Illuminate\Foundation\Application(
 $_ENV[&#39;APP_BASE_PATH&#39;] ?? 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);
// 返回应用实例
return $app;
登入後複製

3、在建立應用程式實例(Application.php)的建構函式中,將基本綁定註冊到容器中,並註冊了所有的基本服務提供者,以及在容器中註冊核心類別名稱

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

    /**
     * Register the basic bindings into the container.
     *
     * @return void
     */
    protected function registerBaseBindings()
    {
        static::setInstance($this);
        $this->instance(&#39;app&#39;, $this);
        $this->instance(Container::class, $this);
        $this->singleton(Mix::class);
        $this->instance(PackageManifest::class, new PackageManifest(
            new Filesystem, $this->basePath(), $this->getCachedPackagesPath()
        ));
        # 注:instance方法为将...注册为共享实例,singleton方法为将...注册为共享绑定
    }
登入後複製

3.2、註冊所有基本服務提供者(事件,日誌,路由)

protected function registerBaseServiceProviders()
    {
        $this->register(new EventServiceProvider($this));
        $this->register(new LogServiceProvider($this));
        $this->register(new RoutingServiceProvider($this));
    }
登入後複製

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

4、上面完成了類別的自動載入、服務提供者註冊、核心類別的綁定、以及基本註冊的綁定

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__.&#39;/../bootstrap/app.php&#39;;这里面进行绑定的,实际指向的就是App\Http\Kernel::class这个类
登入後複製

5.2、這裡對http 請求進行處理

$response = $kernel->handle(
 $request = Illuminate\Http\Request::capture());
登入後複製

進入$kernel 所代表的類別App\Http\Kernel.php 中,我們可以看到其實裡面只是定義了一些中間件相關的內容,並沒有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[&#39;events&#39;]->dispatch(
        new Events\RequestHandled($request, $response)
    );
    return $response;}
登入後複製

6、處理Http 請求(將request 綁定到共用實例,並使用管道模式處理使用者請求)

vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php的handle方法// 最核心的处理http请求的地方$response = $this->sendRequestThroughRouter($request);protected function sendRequestThroughRouter($request){
    // 将请求$request绑定到共享实例
    $this->app->instance(&#39;request&#39;, $request);
    // 将请求request从已解析的门面实例中清除(因为已经绑定到共享实例中了,没必要再浪费资源了)
    Facade::clearResolvedInstance(&#39;request&#39;);
    // 引导应用程序进行HTTP请求
    $this->bootstrap();【7、8】    // 进入管道模式,经过中间件,然后处理用户的请求【9、10】
    return (new Pipeline($this->app))
                ->send($request)
                ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
                ->then($this->dispatchToRouter());}
登入後複製

7、在bootstrap 方法中,執行給定的引導類別數組$bootstrappers,載入設定檔、環境變數、服務提供者、門面、例外處理、引導提供者,非常重要的一步,位置在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());
    }}
登入後複製
/**
 * 运行给定的引导类数组
 *
 * @param  string[]  $bootstrappers
 * @return void
 */public function bootstrapWith(array $bootstrappers){
    $this->hasBeenBootstrapped = true;
    foreach ($bootstrappers as $bootstrapper) {
        $this[&#39;events&#39;]->dispatch(&#39;bootstrapping: &#39;.$bootstrapper, [$this]);
        $this->make($bootstrapper)->bootstrap($this);
        $this[&#39;events&#39;]->dispatch(&#39;bootstrapped: &#39;.$bootstrapper, [$this]);
    }}/**
 * Get the bootstrap classes for the application.
 *
 * @return array
 */protected function bootstrappers(){
    return $this->bootstrappers;}/**
 * 应用程序的引导类
 *
 * @var array
 */protected $bootstrappers = [
    // 加载环境变量
    \Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class,
    // 加载config配置文件【重点】
    \Illuminate\Foundation\Bootstrap\LoadConfiguration::class,
    // 加载异常处理
    \Illuminate\Foundation\Bootstrap\HandleExceptions::class,
    // 加载门面注册
    \Illuminate\Foundation\Bootstrap\RegisterFacades::class,
    // 加载在config/app.php中的providers数组里所定义的服务【8 重点】
    \Illuminate\Foundation\Bootstrap\RegisterProviders::class,
    // 记载引导提供者
    \Illuminate\Foundation\Bootstrap\BootProviders::class,];
登入後複製

8、載入config/app.php 中的providers 陣列裡定義的服務

Illuminate\Auth\AuthServiceProvider::class,Illuminate\Broadcasting\BroadcastServiceProvider::class,....../**
 * 自己添加的服务提供者 */\App\Providers\HelperServiceProvider::class,
登入後複製

可以看到,關於常用的Redis、session、queue、auth、database、Route 等服務都是在這裡進行載入的

9、使用管道模式處理使用者請求,先經過中間件進行處理和過濾

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

/**
 * 应用程序的全局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、經過中間件處理後,再進行請求分發(包括查找匹配路由)

/**
 * 10.1 通过中间件/路由器发送给定的请求
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
 protected function sendRequestThroughRouter($request){
    ...
    return (new Pipeline($this->app))
        ...
        // 进行请求分发
        ->then($this->dispatchToRouter());}
登入後複製
/**
 * 10.2 获取路由调度程序回调
 *
 * @return \Closure
 */protected function dispatchToRouter(){
    return function ($request) {
        $this->app->instance(&#39;request&#39;, $request);
        // 将请求发送到应用程序
        return $this->router->dispatch($request);
    };}
登入後複製
/**
 * 10.3 将请求发送到应用程序
 *
 * @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 将请求分派到路由并返回响应【重点在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),然后根据请求类型选择对应的路由
    $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;}
登入後複製

到現在,已經找到與請求相符的路由了,之後將運行了,也就是10.4 中的runRoute 方法

/**
 * 10.7 返回给定路线的响应
 *
 * @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 在栈中运行路由,先检查有没有控制器中间件,如果有先运行控制器中间件
 *
 * @param  \Illuminate\Routing\Route  $route
 * @param  \Illuminate\Http\Request  $request
 * @return mixed
 */protected function runRouteWithinStack(Route $route, Request $request){
    $shouldSkipMiddleware = $this->container->bound(&#39;middleware.disable&#39;) &&
                            $this->container->make(&#39;middleware.disable&#39;) === 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 最后一步,运行控制器的方法,处理数据
     * @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、運行路由並返回響應(重點)
可以看到,10.7 中有一個方法是prepareResponse,該方法是從給定值建立回應實例,而runRouteWithinStack 方法則是在堆疊中運行路由,也就是說, http 的請求和回應都將在這裡完成。

總結

到此為止,整個Laravel 框架的運作流程就分析完畢了,揭開了Laravel 框架的神秘面紗,其中為了文章的可讀性,只給了核心代碼,需要大家結合文章自行去閱讀源碼,需要注意的是必須了解文章中提到的準備知識,這是閱讀框架源碼的前提和基礎,希望大家有所收穫,下車! ! !                                           為  

以上是一篇文章帶你徹底搞懂Laravel運作原理!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Laravel和CodeIgniter的最新版本對比 Laravel和CodeIgniter的最新版本對比 Jun 05, 2024 pm 05:29 PM

Laravel9和CodeIgniter4的最新版本提供了更新的功能和改進。 Laravel9採用MVC架構,提供資料庫遷移、驗證及模板引擎等功能。 CodeIgniter4採用HMVC架構,提供路由、ORM和快取。在性能方面,Laravel9的基於服務提供者設計模式和CodeIgniter4的輕量級框架使其具有出色的性能。在實際應用中,Laravel9適用於需要靈活性和強大功能的複雜項目,而CodeIgniter4適用於快速開發和小型應用程式。

Laravel 和 CodeIgniter 中資料處理能力的比較如何? Laravel 和 CodeIgniter 中資料處理能力的比較如何? Jun 01, 2024 pm 01:34 PM

比較Laravel和CodeIgniter的資料處理能力:ORM:Laravel使用EloquentORM,提供類別物件關係映射,而CodeIgniter使用ActiveRecord,將資料庫模型表示為PHP類別的子類別。查詢建構器:Laravel具有靈活的鍊式查詢API,而CodeIgniter的查詢建構器更簡單,基於陣列。資料驗證:Laravel提供了一個Validator類,支援自訂驗證規則,而CodeIgniter的驗證功能內建較少,需要手動編碼自訂規則。實戰案例:用戶註冊範例展示了Lar

Laravel - Artisan 指令 Laravel - Artisan 指令 Aug 27, 2024 am 10:51 AM

Laravel - Artisan 指令 - Laravel 5.7 提供了處理和測試新指令的新方法。它包括測試 artisan 命令的新功能,下面提到了演示?

Laravel 和 CodeIgniter 對於初學者來說哪一個比較友善? Laravel 和 CodeIgniter 對於初學者來說哪一個比較友善? Jun 05, 2024 pm 07:50 PM

對於初學者來說,CodeIgniter的學習曲線更平緩,功能較少,但涵蓋了基本需求。 Laravel提供了更廣泛的功能集,但學習曲線稍陡。在性能方面,Laravel和CodeIgniter都表現出色。 Laravel有更廣泛的文件和活躍的社群支持,而CodeIgniter更簡單、輕量級,具有強大的安全功能。在建立部落格應用程式的實戰案例中,Laravel的EloquentORM簡化了資料操作,而CodeIgniter需要更多的手動配置。

Laravel和CodeIgniter:哪種框架更適合大型專案? Laravel和CodeIgniter:哪種框架更適合大型專案? Jun 04, 2024 am 09:09 AM

在選擇大型專案框架時,Laravel和CodeIgniter各有優勢。 Laravel針對企業級應用程式而設計,提供模組化設計、相依性注入和強大的功能集。 CodeIgniter是一款輕量級框架,更適合小型到中型項目,強調速度和易用性。對於具有複雜需求和大量用戶的大型項目,Laravel的強大功能和可擴展性更為合適。而對於簡單專案或資源有限的情況下,CodeIgniter的輕量級和快速開發能力則較為理想。

PHP 企業級應用微服務架構設計問答 PHP 企業級應用微服務架構設計問答 May 07, 2024 am 09:36 AM

微服務架構使用PHP框架(如Symfony和Laravel)來實現微服務,並遵循RESTful原則和標準資料格式來設計API。微服務透過訊息佇列、HTTP請求或gRPC進行通信,並使用工具(如Prometheus和ELKStack)進行監控和故障排除。

Laravel和CodeIgniter:哪種框架比較適合小型專案? Laravel和CodeIgniter:哪種框架比較適合小型專案? Jun 04, 2024 pm 05:29 PM

對於小型項目,Laravel適用於大型項目,需要強大的功能和安全性。 CodeIgniter適用於非常小的項目,需要輕量級和易用性。

Laravel 和 CodeIgniter 的模板引擎哪一個比較好? Laravel 和 CodeIgniter 的模板引擎哪一個比較好? Jun 03, 2024 am 11:30 AM

比較了Laravel的Blade和CodeIgniter的Twig模板引擎,根據專案需求和個人偏好進行選擇:Blade基於MVC語法,鼓勵良好程式碼組織和模板繼承。 Twig是第三方函式庫,提供靈活語法、強大過濾器、擴充支援和安全沙箱。

See all articles