我一直在寻找同样的东西。有一个名为Fractal的很好的php库让你实现它:http://fractal.thephpleague.com/
简要地解释一下lib,为你的每个模型创建一个Transformer,它将在你的模型属性和需要的模型属性之间进行映射使用API暴露。
class BookTransformer extends Fractal\TransformerAbstract
{
public function transform(Book $book)
{
return [
'id' => (int) $book->id,
'title' => $book->title,
'year' => $book->yr,
];
}
}
在你还可以设置关系的变压器,这种模式有:
class BookTransformer extends TransformerAbstract
{
/**
* List of resources relations that can be used
*
* @var array
*/
protected $availableEmbeds = [
'author'
];
/**
* Turn this item object into a generic array
*
* @return array
*/
public function transform(Book $book)
{
return [
'id' => (int) $book->id,
'title' => $book->title,
'year' => $book->yr,
];
}
/**
* Here we are embeding the author of the book
* using it's own transformer
*/
public function embedAuthor(Book $book)
{
$author = $book->author;
return $this->item($author, new AuthorTransformer);
}
}
所以在最后,你会打电话给
$fractal = new Fractal\Manager();
$resource = new Fractal\Resource\Collection($books, new BookTransformer);
$json = $fractal->createData($resource)->toJson();
这并不容易来描述所有的潜在在一个答案中的分形,但你真的应该试试看。 我和Yii一起使用它,所以如果你有一些问题不要犹豫!