Laravel框架生命周期與原理分析
本文實(shí)例講述了Laravel框架生命周期與原理。分享給大家供大家參考,具體如下:
引言:
如果你對(duì)一件工具的使用原理了如指掌,那么你在用這件工具的時(shí)候會(huì)充滿信心!
正文:
一旦用戶(瀏覽器)發(fā)送了一個(gè)HTTP請(qǐng)求,我們的apache或者nginx一般都轉(zhuǎn)到index.php,因此,之后的一系列步驟都是從index.php開始的,我們先來看一看這個(gè)文件代碼。
<?php require __DIR__.'/../bootstrap/autoload.php'; $app = require_once __DIR__.'/../bootstrap/app.php'; /* |-------------------------------------------------------------------------- | Run The Application |-------------------------------------------------------------------------- | | Once we have the application, we can handle the incoming request | through the kernel, and send the associated response back to | the client's browser allowing them to enjoy the creative | and wonderful application we have prepared for them. | */ $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class); $response = $kernel->handle( $request = Illuminate\Http\Request::capture() ); $response->send(); $kernel->terminate($request, $response);
作者在注釋里談了kernel的作用,kernel的作用,kernel處理來訪的請(qǐng)求,并且發(fā)送相應(yīng)返回給用戶瀏覽器。
這里又涉及到了一個(gè)app對(duì)象,所以附上app對(duì)象,所以附上app對(duì)象的源碼,這份源碼是\bootstrap\app.php
<?php /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | | The first thing we will do is create a new Laravel application instance | which serves as the "glue" for all the components of Laravel, and is | the IoC container for the system binding all of the various parts. | */ $app = new Illuminate\Foundation\Application( realpath(__DIR__.'/../') ); /* |-------------------------------------------------------------------------- | Bind Important Interfaces |-------------------------------------------------------------------------- | | Next, we need to bind some important interfaces into the container so | we will be able to resolve them when needed. The kernels serve the | incoming requests to this application from both the web and CLI. | */ $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 The Application |-------------------------------------------------------------------------- | | This script returns the application instance. The instance is given to | the calling script so we can separate the building of the instances | from the actual running of the application and sending responses. | */ return $app;
請(qǐng)看app變量是Illuminate\Foundation\Application類的對(duì)象,所以調(diào)用了這個(gè)類的構(gòu)造函數(shù),具體做了什么事,我們看源碼。
public function __construct($basePath = null) { if ($basePath) { $this->setBasePath($basePath); } $this->registerBaseBindings(); $this->registerBaseServiceProviders(); $this->registerCoreContainerAliases(); }
構(gòu)造器做了3件事,前兩件事很好理解,創(chuàng)建Container,注冊(cè)了ServiceProvider,看代碼
/** * Register the basic bindings into the container. * * @return void */ protected function registerBaseBindings() { static::setInstance($this); $this->instance('app', $this); $this->instance(Container::class, $this); } /** * Register all of the base service providers. * * @return void */ protected function registerBaseServiceProviders() { $this->register(new EventServiceProvider($this)); $this->register(new LogServiceProvider($this)); $this->register(new RoutingServiceProvider($this)); }
最后一件事,是做了個(gè)很大的數(shù)組,定義了大量的別名,側(cè)面體現(xiàn)程序員是聰明的懶人。
/** * Register the core class aliases in the container. * * @return void */ public function registerCoreContainerAliases() { $aliases = [ 'app' => [\Illuminate\Foundation\Application::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::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\Contracts\Hashing\Hasher::class], 'translator' => [\Illuminate\Translation\Translator::class, \Illuminate\Contracts\Translation\Translator::class], 'log' => [\Illuminate\Log\Writer::class, \Illuminate\Contracts\Logging\Log::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], ]; foreach ($aliases as $key => $aliases) { foreach ($aliases as $alias) { $this->alias($key, $alias); } } }
這里出現(xiàn)了一個(gè)instance函數(shù),其實(shí)這并不是Application類的函數(shù),而是Application類的父類Container類的函數(shù)
/** * Register an existing instance as shared in the container. * * @param string $abstract * @param mixed $instance * @return void */ public function instance($abstract, $instance) { $this->removeAbstractAlias($abstract); unset($this->aliases[$abstract]); // We'll check to determine if this type has been bound before, and if it has // we will fire the rebound callbacks registered with the container and it // can be updated with consuming classes that have gotten resolved here. $this->instances[$abstract] = $instance; if ($this->bound($abstract)) { $this->rebound($abstract); } }
Application是Container的子類,所以$app
不僅是Application類的對(duì)象,還是Container的對(duì)象,所以,新出現(xiàn)的singleton函數(shù)我們就可以到Container類的源代碼文件里查。bind函數(shù)和singleton的區(qū)別見這篇博文。
singleton這個(gè)函數(shù),前一個(gè)參數(shù)是實(shí)際類名,后一個(gè)參數(shù)是類的“別名”。
$app
對(duì)象聲明了3個(gè)單例模型對(duì)象,分別是HttpKernel,ConsoleKernel,ExceptionHandler。請(qǐng)注意,這里并沒有創(chuàng)建對(duì)象,只是聲明,也只是起了一個(gè)“別名”。
大家有沒有發(fā)現(xiàn),index.php中也有一個(gè)$kernel變量,但是只保存了make出來的HttpKernel變量,因此本文不再討論,ConsoleKernel,ExceptionHandler。。。
繼續(xù)在文件夾下找到App\Http\Kernel.php,既然我們把實(shí)際的HttpKernel做的事情都寫在這個(gè)php文件里,就從這份代碼里看看究竟做了哪些事?
<?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, //\App\Http\Middleware\MyMiddleware::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\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ], 'api' => [ 'throttle:60,1', ], ]; /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'mymiddleware'=>\App\Http\Middleware\MyMiddleware::class, ]; }
一目了然,HttpKernel里定義了中間件數(shù)組。
該做的做完了,就開始了請(qǐng)求到響應(yīng)的過程,見index.php
$response = $kernel->handle( $request = Illuminate\Http\Request::capture() ); $response->send();
最后在中止,釋放所有資源。
/** * Call the terminate method on any terminable middleware. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Response $response * @return void */ public function terminate($request, $response) { $this->terminateMiddleware($request, $response); $this->app->terminate(); }
總結(jié)一下,簡(jiǎn)單歸納整個(gè)過程就是:
1.index.php加載\bootstrap\app.php,在Application類的構(gòu)造函數(shù)中創(chuàng)建Container,注冊(cè)了ServiceProvider,定義了別名數(shù)組,然后用app變量保存構(gòu)造函數(shù)構(gòu)造出來的對(duì)象。
2.使用app這個(gè)對(duì)象,創(chuàng)建1個(gè)單例模式的對(duì)象HttpKernel,在創(chuàng)建HttpKernel時(shí)調(diào)用了構(gòu)造函數(shù),完成了中間件的聲明。
3.以上這些工作都是在請(qǐng)求來訪之前完成的,接下來開始等待請(qǐng)求,然后就是:接受到請(qǐng)求-->處理請(qǐng)求-->發(fā)送響應(yīng)-->中止app變量
更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進(jìn)階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對(duì)大家基于Laravel框架的PHP程序設(shè)計(jì)有所幫助。
- Laravel6.2中用于用戶登錄的新密碼確認(rèn)流程詳解
- Laravel 5框架學(xué)習(xí)之模型、控制器、視圖基礎(chǔ)流程
- Laravel 5.4重新登錄實(shí)現(xiàn)跳轉(zhuǎn)到登錄前頁面的原理和方法
- Laravel中間件實(shí)現(xiàn)原理詳解
- Laravel模型事件的實(shí)現(xiàn)原理詳解
- 淺談Laravel隊(duì)列實(shí)現(xiàn)原理解決問題記錄
- Laravel框架隊(duì)列原理與用法分析
- Laravel認(rèn)證原理以及完全自定義認(rèn)證詳解
- laravel框架模型中非靜態(tài)方法也能靜態(tài)調(diào)用的原理分析
- 淺談laravel aliases別名的原理
- laravel 框架執(zhí)行流程與原理簡(jiǎn)單分析
相關(guān)文章
PHP 文本文章分頁代碼 按標(biāo)記或長度(不涉及數(shù)據(jù)庫)
PHP文本分頁,按標(biāo)記或者長度分頁,非傳統(tǒng)的數(shù)據(jù)庫分頁。廢話不多說,客觀如有意可直接看代碼2012-06-06php中header跳轉(zhuǎn)使用include包含解決參數(shù)丟失問題
在一個(gè)項(xiàng)目中遇到的問題,當(dāng)用戶登錄成功時(shí),用header跳轉(zhuǎn)到首頁,一直都是錯(cuò),無法跳到你要的頁面。最終度娘了許久才找到解決方法,這里分享給大家。2015-05-05php合并數(shù)組并保留鍵值的實(shí)現(xiàn)方法
下面小編就為大家分享一篇php合并數(shù)組并保留鍵值的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03Thinkphp 框架基礎(chǔ)之源碼獲取、環(huán)境要求與目錄結(jié)構(gòu)分析
這篇文章主要介紹了Thinkphp 框架基礎(chǔ)之源碼獲取、環(huán)境要求與目錄結(jié)構(gòu),簡(jiǎn)單分析了Thinkphp源碼的獲取方法、下載地址、安裝環(huán)境要求以及目錄結(jié)構(gòu),需要的朋友可以參考下2020-04-04php使用flock阻塞寫入文件和非阻塞寫入文件的實(shí)例講解
下面小編就為大家?guī)硪黄猵hp使用flock阻塞寫入文件和非阻塞寫入文件的實(shí)例講解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07AJAX PHP無刷新form表單提交的簡(jiǎn)單實(shí)現(xiàn)(推薦)
下面小編就為大家?guī)硪黄狝JAX PHP無刷新form表單提交的簡(jiǎn)單實(shí)現(xiàn)(推薦)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-09-09PHPMailer使用教程(PHPMailer發(fā)送郵件實(shí)例分析)
php雖然提供了mail()函數(shù),但并不好用,而PHPMailer是一個(gè)不錯(cuò)的郵件發(fā)送工具,接下來將詳細(xì)介紹,需要了解的朋友可以參考下2012-12-12php獲取用戶真實(shí)IP和防刷機(jī)制的實(shí)例代碼
這篇文章主要介紹了php獲取用戶真實(shí)IP和防刷機(jī)制,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2018-11-11PHP網(wǎng)頁安全認(rèn)證的實(shí)例詳解
這篇文章主要介紹了PHP網(wǎng)頁安全認(rèn)證的實(shí)例詳解的相關(guān)資料,這里提供了兩種實(shí)現(xiàn)方法,一種基于數(shù)據(jù)庫另一種不基于數(shù)據(jù)庫的方法,希望通過本能幫助到大家,需要的朋友可以參考下2017-09-09