Laravel 5.5 為響應請求提供的可響應介面
阿新 • • 發佈:2022-05-02
Laravel 5.5 的路由中增加了一種新的返回型別:可相應介面(Responsable)。該介面允許物件在從控制器或者閉包路由中返回時自動被轉化為標準的 HTTP 響應介面。任何實現 Responsable 介面的物件必須實現一個名為 toResponse()
的方法,該方法將物件轉化為 HTTP 響應物件。看示例:
use IlluminateContractsSupportResponsable; class ExampleObject implements Responsable { public function __construct($name = null) { $this->name = $name ?? 'Teapot'; } public function status() { switch(strtolower($this->name)) { case 'teapot': return 418; default: return 200; } } public function toResponse() { return response( "Hello {$this->name}", $this->status(), ['X-Person' => $this->name] ); } }
在路由中使用這個 ExampleObject
的時候,你可以這樣做:
Route::get('/hello', function() {
return new ExampleObject(request('name'));
});
在 Laravel 框架中,Route
類如今可以在準備響應內容時檢查這種(實現了 Responsable 介面的)型別:
if ($response instanceof Responsable) {
$response = $response->toResponse();
}
假如你在 AppHttpResponses
名稱空間下用多個響應型別來組織你的響應內容,可以參考下面這個示例。該示例演示瞭如何支援 Posts
posts = $posts; } public function toResponse() { return response()->json($this->transformPosts()); } protected function transformPosts() { return $this->posts->map(function ($post) { return [ 'title' => $post->title, 'description' => $post->description, 'body' => $post->body, 'published_date' => $post->published_at->toIso8601String(), 'created' => $post->created_at->toIso8601String(), ]; }); } }
以上只是一個模擬簡單應用場景的基礎示例:返回一個 JSON 響應,但你希望響應層不是簡單地用內建實現把物件 JSON 化,而是要做一些內容處理。以上示例同時假設 AppHttpResponsesResponse
這個類能提供一些基礎的功能。當然響應層也可以包含一些轉換程式碼(類似Fractal),而不是直接在控制器裡做這樣的轉換。
與上面示例中的 PostIndexResponse
類協作的控制器程式碼類似以下這樣:
<!--?php
namespace AppHttpControllers;
use AppHttpResponses;
class PostsController extends Controller
{
public function index()
{
$posts = AppPost::all();
return new ResponsesPostIndexResponse($posts);
}
}
</pre-->
<p>
如果你想了解更多有關這個介面的細節,可以檢視專案中<a href="https://github.com/laravel/framework/commit/c0c89fd73cebf9ed56e6c5e69ad35106df03d9db">相關程式碼的 commit</a>.</p>
<div id="copyright">
<img alt="" src="https://secure.gravatar.com/avatar/16a16bbe262d086712d25908c61a034b?s=55&d=mm&r=g" srcset="https://secure.gravatar.com/avatar/16a16bbe262d086712d25908c61a034b?s=110&d=mm&r=g 2x" class="avatar avatar-55 photo" height="55" width="55"> <p>作者:<a itemprop="author" itemscope="" itemtype="http://schema.org/Person" href="https://ofcss.com" title="小李刀刀"><span itemprop="name">小李刀刀</span></a><br>
原文連結:<a href="https://ofcss.com/2017/10/31/laravel-55-responsable-interface-for-responses.html" title="Laravel 5.5 為響應請求提供的可響應介面">Laravel 5.5 為響應請求提供的可響應介面</a><br>
<a href="https://ofcss.com" title="裁紙刀下">裁紙刀下</a>版權所有,允許非商業用途轉載,轉載時請原樣轉載並標明來源、作者,保留原文連結。</p>
</div>