相關(guān)關(guān)鍵詞
關(guān)于我們
最新文章
Laravel 5.5中為響應請求提供的可響應接口詳解
前言
Laravel 5.5 也將會是接下來的一個 LTS(長期支持)版本。 這就意味著它擁有兩年修復以及三年的安全更新支持。Laravel 5.1 也是如此,不過它兩年的錯誤修復支持將在今年結(jié)束。
Laravel 5.5 的路由中增加了一種新的返回類型:可相應接口( Responsable )。該接口允許對象在從控制器或者閉包路由中返回時自動被轉(zhuǎn)化為標準的 HTTP 響應接口。任何實現(xiàn) Responsable 接口的對象必須實現(xiàn)一個名為 toResponse()
的方法,該方法將對象轉(zhuǎn)化為 HTTP 響應對象。
看示例:
use Illuminate\Contracts\Support\Responsable; 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] ); } }