伺服器端把關
一次 Linker 呼叫經過的關卡
權限排在參數驗證之前:沒權限的人看不到欄位規則。
實踐
每支方法都要回答「誰可以呼叫」
php
#[RequiresAuth] // 類別層:整個元件都要登入
class InvoiceLinker extends LinkerComponent
{
#[Computable]
#[Validate(['id' => 'required|integer'])]
#[Authorize('view', Invoice::class, arg: 'id')] // 方法層:這張發票是不是他的
public function show(array $args): LinkerResponse { … }
}- 規則只能疊加、不能放寬,新方法忘了標會跟其他方法一樣嚴格。
#[Authorize]帶 model 時會用arg取 id、find()載入,找不到就拒絕。- 頁面路由上的
auth、can:不作用在 Linker 呼叫,因為 Linker 端點是共用的。
不要相信「前端已經檢查過了」
php
// ❌ 前端送來的 total 不可信
public function checkout(array $args): LinkerResponse
{
Order::create(['total' => $args['total']]);
}
// ✅ 伺服器自己算
public function checkout(array $args): LinkerResponse
{
$total = Cart::for(auth()->user())->total();
Order::create(['total' => $total]);
}用伺服器狀態做流程 guard
php
#[Computable]
public function submit(array $args): LinkerResponse
{
if ($this->get('step') !== 3) { // 前端改不到這個值
return LinkerResponse::policy();
}
…
}Stateless 的寫入要自己保證冪等
Stateless 沒有實例鎖,同一個 URL 可以並行。寫入請用 DB transaction、unique constraint 或 idempotency key。
renderBlade 的 params 要挑
php
public function renderCallSafely(array $params = [], string $method = 'components'): View
{
// ✅ 白名單 + 型別
$mode = in_array($params['mode'] ?? '', ['list', 'detail'], true) ? $params['mode'] : 'list';
$id = (int) ($params['id'] ?? 0);
// ❌ 不要整包丟進查詢或 view
// return view('x', $params);
}@renderInline 不經過請求驗證層,Controller 白名單檢查在它內部強制執行。
快取要含使用者
#[Computable(cache: true)] 的 key 一定混入 user id 與參數;自己寫快取時也要這樣做,否則就是跨使用者洩漏。
除錯輸出
$this->dump() / dd() 只在 APP_DEBUG=true 送出內容。正式環境照樣攔截(不讓 HTML 弄壞 JSON),內容丟掉、只記 warning。正式環境務必 APP_DEBUG=false。
業務程式碼裡的 abort() 與例外
方法裡可以直接 abort(),框架會翻成前端認得的 kind,不會一律變成 fatal:
| 例外 | kind |
|---|---|
abort(401) / abort(403) | policy |
abort(404) | service(「找不到」) |
abort(409) | conflict |
abort(422) | validation |
| 其他 HTTP 例外 | service |
任何其他 Throwable | fatal,並 report() 進 log |
正式環境只給一句固定訊息,例外細節只在 log 裡 —— 例外內容不外洩。