把書架做完整 / 第 8 章
一個請求在 Laravel 的旅程
為書架加一個 /shelf-summary。瀏覽器打開它會得到目前藏書數目,而回應標頭會標明資料來源。這個短小的功能足以看清三個角色:準備依賴的容器、把共同工作放在路由前後的中介層,以及設定應用程式的服務提供者。
跟着網址走一次
- public/index.php
- 啟動應用程式
- 中介層與路由
- 回應送回瀏覽器
網頁伺服器把請求交給 public/index.php。Laravel 載入設定與服務提供者,由 HTTP 核心把請求送進中介層。路由器找到相符的網址與 HTTP 方法,再由相應的路由中介層及處理程式接手。
想像你正在排查 /shelf-summary。404 提醒你先用 route:list 找網址;若網址正確但數量不對,檢查負責計算的物件。若回應內容正確但少了標頭,應回到掛在路由上的中介層。
讓容器供應一個具體類別
在 app 建立 Services 資料夾及以下檔案。這個類別只負責一件事,計算書架上有多少本書。
<?php
namespace App\Services;
use App\Models\Book;
class ShelfSummary
{
public function total(): int
{
return Book::query()->count();
}
}在既有 routes/web.php 的 PHP 區塊末尾加入新路由。Laravel 從參數的型別知道要建立 ShelfSummary 物件,因此你可以直接呼叫 total()。
\Illuminate\Support\Facades\Route::get('/shelf-summary', function (
\App\Services\ShelfSummary $summary
) {
return response()->json(['books' => $summary->total()]);
});在瀏覽器開啟 /shelf-summary。如果書架有三本書,會得到 {"books":3}。新增一本書再重新整理,數字便會增加一。
服務提供者如何決定實作
假設另一項功能要用不同方法計算,例如改讀統計表。先宣告介面,再由現有類別實作它。其他程式只需說出自己需要哪種能力。
<?php
namespace App\Services;
interface CountsBooks
{
public function total(): int;
}class ShelfSummary implements CountsBooks在預設 AppServiceProvider 的 register() 加入下列一行。服務提供者集中設定介面與類別的對應;所有提供者完成 register() 後才進入 boot(),因此依賴其他已註冊服務的啟動工作可放在 boot()。
$this->app->bind(\App\Services\CountsBooks::class, \App\Services\ShelfSummary::class);將 /shelf-summary 路由參數的型別從 \App\Services\ShelfSummary 改成 \App\Services\CountsBooks。重新整理後 JSON 應相同。若出現介面無法實例化的訊息,請核對 bind() 兩端的命名空間。
在回應離開前加一個標頭
php artisan make:middleware MarkShelfResponse保留產生器建立的類別、匯入和 handle() 簽名。將 handle() 的方法內容換成下列三行。$next 把請求交給下一層,取得的回應仍可加上標頭。
$response = $next($request);
$response->headers->set('X-Shelf-Source', 'catalog');
return $response;把 /shelf-summary 路由定義末尾的 }); 改為以下一行,便會只在這個路由使用剛建立的中介層。
})->middleware(\App\Http\Middleware\MarkShelfResponse::class);打開瀏覽器開發者工具的 Network 面板,重載頁面,選取 shelf-summary 的回應標頭,應看到 X-Shelf-Source 等於 catalog。也可在終端機使用 curl -i http://127.0.0.1:8000/shelf-summary;Windows 可用 curl.exe。
動手練習
在 Tinker 直接向容器請求 CountsBooks 介面,檢查實際收到哪個類別,再用該物件讀取數量。
查看參考答案
輸入 $counter = app(\App\Services\CountsBooks::class);,然後分別執行 get_class($counter) 及 $counter->total()。第一個結果應為 App\Services\ShelfSummary,第二個與 /shelf-summary 的 books 相同。