This article mainly introduces you to the relevant information about the responsive interface provided in Laravel 5.5 for responding to requests. The Laravel introduced through the sample code is very detailed and is very useful. Everyone's study or work has certain reference learning value. Friends who need it can follow the editor to learn Laravel .
Preface
Laravel 5.5 will also be the next LTS (long-term support) version. That means it has two years of fixes and three years of security updates. The same goes for Laravel 5.1, although its two years of bug-fix support will end this year.
Laravel 5.5 adds a new return type to routing: Responsable interface. This interface allows objects to be automatically converted into a standard HTTP response interface when returned from a controller or closure route. Any object that implements the Responsable interface must implement a method named toResponse()
, which converts the object into an HTTP response object.
Look at the example:
##
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] ); } }
Route::get('/hello', function() { return new ExampleObject(request('name')); });
if ($response instanceof Responsable) { $response = $response->toResponse(); }
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(), ]; }); } }
Summary
The above is all the content of this article, I hope it can be helpful to everyone.Related recommendations:
How to implement Laravel 5.5 responsive interface
Laravel’s verification code library
Detailed explanation of cross-domain solutions in laravel development
The above is the detailed content of Detailed explanation of the responsive interface provided in Laravel 5.5 for responding to requests_php example. For more information, please follow other related articles on the PHP Chinese website!