noisim / resource
构建JSON响应等资源所需的帮助程序包。
This package is auto-updated.
Last update: 2024-09-27 23:23:56 UTC
README
Resource 是一个用于构建JSON响应等资源的包。我已经使用Phalcon PHP框架对其进行测试。
安装
此包通过 Composer 安装。要安装,只需将其添加到您的 composer.json 文件
{
"require": {
"noisim/resource": "dev-master"
}
}
并运行 composer 以更新依赖项 composer update。
如何使用
假设在我们的应用(可以是任何框架,如Laravel、Phalcon等)中,我们有像 User、Post、Comment 这样的模型。这些模型之间有相互关系。因此,一个用户可以有多个帖子,一个帖子可以有多个评论,一个用户可以有多个评论,一个帖子属于一个用户,一个评论属于一个帖子,一个评论属于一个用户。
无论使用哪种框架,我们都可以通过模型以这种形式访问这些关系
<?php $user->posts; $post->user; $post->comments; $comment->post; $user->comments; $comment->user;
有时,当我们想从我们的应用路由(API端点)返回JSON时,我们不想返回包含所有字段的整个模型对象,或者有时我们想返回模型的核心字段以及任何关系字段。在这种情况下,我们需要像 Resource 这样的包,它在这些情况下非常有帮助。
对于我们的示例,我们必须构建3个类,这些类将扩展 \Noisim\Resource\Resource 类。
<?php use \Noisim\Resource\Resource; class UserResource extends Resource { public function toArray() { return [ "id" => $this->id, "name" => $this->name, "email" => $this->email, "createdAt" => $this->createdAt ]; } } class PostResource extends Resource { public function toArray() { return [ "id" => $this->id, "userId" => $this->userId, "title" => $this->title, "content" => $this->content, "createdAt" => $this->createdAt ]; } } class CommentResource extends Resource { public function toArray() { return [ "id" => $this->id, "postId" => $this->postId, "userId" => $this->userId, "content" => $this->content, "createdAt" => $this->createdAt ]; } }
简单示例
在我们的控制器中,我们可以这样返回资源
<?php class PostController extends Controller { public function getAll() { $posts = $this->funnelService->getAll(); // We pass the list of posts as an argument to the PostResource return new PostResource($posts); } public function getById($id) { $post = $this->funnelService->getById($id); // We pass the post as an argument to the PostResource return new PostResource($post); }
根据框架的不同,将此类响应转换为JSON的处理需要由框架本身来处理。 PostResource 是一个实现了 JsonSerializable 的实例,可以轻松序列化为JSON。
返回额外的关系字段
<?php class PostController extends Controller { public function getAll() { $posts = $this->funnelService->getAll(); // We pass the list of posts as an argument to the PostResource return (new PostResource($posts))->with(function($post) { return [ "comments" => new CommentResource($post->comments) ]; }); }
上面的示例为每个帖子实例附加了一个 comments 字段。 comments 包含相关帖子的评论列表。在这种情况下,我们使用了一个接受闭包作为参数的 with 方法。
过滤字段
<?php class PostController extends Controller { public function getAll() { $posts = $this->funnelService->getAll(); // We pass the list of posts as an argument to the PostResource return (new PostResource($posts))->only(['id', 'title', 'content']); }
在这个示例中,我们使用了 only 方法来过滤字段,返回的数据将只包含指定的字段。如果我们想排除一些字段,可以使用 except 方法。
<?php return (new PostResource($posts))->except(['userId', 'createdAt']);