上篇介紹了 Laravel 的路由註冊機制“Laravel 4 的路由是如何完成註冊的?”作爲這個系列的最後一講,本篇將要爲大家介紹的,是執行了 $app->run() 之後所發生的事,以及這個過程中涉及到的應用程序事件。
在完成了路由的註冊後,緊接着執行的就是 public/index.php 中的 $app->run(); 讓我們來看一下 run 方法的源碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
function
run() { //
調度路由返回響應實例 $response
= $this ->dispatch( $this [ 'request' ]); //
執行 close 應用程序事件 $this [ 'router' ]->callCloseFilter( $this [ 'request' ],
$response ); //
發送響應 $response ->send(); //
執行 finish 應用程序事件 $this [ 'router' ]->callFinishFilter( $this [ 'request' ],
$response ); } |
下面是整個流程的分析:
- 第4行,執行了路由調度操作 dispatch
- 執行應用程序事件 App::before(function($request){})
- 執行 Illuminate\Routing\Route.php 的 run 方法
- 執行 Route::filter($route, $request) 前置操作
- 最終業務回調,取得響應實例(這裏執行了之前註冊進路由的回調函數)
- 執行 Route::filter($route, $request, $response) 後置操作
- 執行應用程序事件 App::after(function($request, $response){})
- 第7行,執行應用程序事件 App::close(function($request, $response){})
- 第10行,發送 1-2-2 中獲取的響應實例
- 第13行,執行應用程序事件 App::finish(function($request, $response){})
- 最後在 public/index.php 中的 $app->shutdown() 時,執行最後的應用程序事件 App::shutdown(function($application){})