这篇文章主要给大家介绍了关于laravel 5.5中为响应请求提供的可响应接口的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
前言
laravel 5.5 也将会是接下来的一个 lts(长期支持)版本。 这就意味着它拥有两年修复以及三年的安全更新支持。laravel 5.1 也是如此,不过它两年的错误修复支持将在今年结束。
laravel 5.5 的路由中增加了一种新的返回类型:可相应接口( responsable )。该接口允许对象在从控制器或者闭包路由中返回时自动被转化为标准的 http 响应接口。任何实现 responsable 接口的对象必须实现一个名为 toresponse() 的方法,该方法将对象转化为 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] ); }}
在路由中使用这个 exampleobject 的时候,你可以这样做:
route::get('/hello', function() { return new exampleobject(request('name'));});
在 laravel 框架中, route 类如今可以在准备响应内容时检查这种(实现了 responsable 接口的)类型:
if ($response instanceof responsable) { $response = $response->toresponse();}
假如你在 app\http\responses 命名空间下用多个响应类型来组织你的响应内容,可以参考下面这个示例。该示例演示了如何支持 posts (多个实例组成的 collection):
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 化,而是要做一些内容处理。以上示例同时假设 app\http\responses\response 这个类能提供一些基础的功能。当然响应层也可以包含一些转换代码(类似 fractal ),而不是直接在控制器里做这样的转换。
与上面示例中的 postindexresponse 类协作的控制器代码类似以下这样:
如果你想了解更多有关这个接口的细节,可以查看项目中 相关代码的 commit .
总结
您可能感兴趣的文章:php操作zip在不解压缩包的情况下显示压缩包中的图片相关讲解
php实现签到功能的方法实例分析de详解
解决linux下php-fpm进程过多导致内存耗尽问题详解
以上就是laravel 5.5中为响应请求提供的可响应接口的详解的详细内容。