Rumah >pembangunan bahagian belakang >tutorial php >Penyesuaian Respons Sumber di API Laravel
withResponse
Ini amat berguna untuk membina API yang mantap yang perlu menyampaikan metadata, butiran versi, atau tajuk tersuai kepada pelanggan.
inilah contoh asas:
Contoh ini menunjukkan penyesuaian tindak balas API yang lebih komprehensif:
class UserResource extends JsonResource { public function withResponse($request, $response) { $response->header('X-Resource-Type', 'User'); } }
Dengan memanfaatkan kaedah
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Request; class DocumentResource extends JsonResource { public function toArray(Request $request): array { return [ 'id' => $this->id, 'title' => $this->title, 'content' => $this->when( $request->user()->canViewContent($this->resource), $this->content ), 'created_at' => $this->created_at, 'updated_at' => $this->updated_at ]; } public function withResponse(Request $request, $response) { $response->header('X-Document-ID', $this->id); if ($this->is_public) { $response->header('Cache-Control', 'public, max-age=3600'); $response->header('ETag', md5($this->updated_at)); } if ($this->wasRecentlyCreated) { $response->setStatusCode(201); } if ($request->has('include_legacy')) { $response->header('X-Deprecated-Fields', 'legacy_format,old_structure'); $response->header('X-Deprecation-Date', '2024-07-01'); } } }, sumber API anda berkembang dari pemegang data semata -mata ke dalam respons HTTP yang disesuaikan sepenuhnya, memperkayakan API anda dengan metadata penting bersama data teras.
Atas ialah kandungan terperinci Penyesuaian Respons Sumber di API Laravel. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!