我们知道laravel 5.5是很重要的一个版本,在laravel 5.5 的路由中增加了一种新的返回类型:可相应接口( responsable )。今天就给大家带来一个案例来详细介绍一下。
看示例:
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 类协作的控制器代码类似以下这样:
免费 盛世企业网站管理系统(SnSee)系统完全免费使用,无任何功能模块使用限制,在使用过程中如遇到相关问题可以去官方论坛参与讨论。开源 系统Web代码完全开源,在您使用过程中可以根据自已实际情况加以调整或修改,完全可以满足您的需求。强大且灵活 独创的多语言功能,可以直接在后台自由设定语言版本,其语言版本不限数量,可根据自已需要进行任意设置;系统各模块可在后台自由设置及开启;强大且适用的后台管理支
相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
相关阅读:









