为了改变 Laravel 5.4 RESTful API 发送的 JSON 输出,我使用了 thephpleague 的 Fractal 包。因为将来会添加分页,所以集合使用默认的 DataArraySerializer 并且单个项目使用 ArraySerializer 很重要。还需要为更深的嵌套对象赋予相同的结构。我怎样才能实现这一点(全球或不)?
class TreeTransformer extends TransformerAbstract {
protected $defaultIncludes = [
'type',
'branches'
];
public function transform(Tree $tree) {
return [
'id' => (int)$tree->id,
'name' => (string)$tree->name
];
}
public function includeType(Tree $tree) {
return $this->item($tree->type, new TypeTransformer()); // Should be ArraySerializer
}
public function includeBranches(Tree $tree) {
return $this->collection($tree->branches, new BranchTransformer()); // Should stay DataArraySerializer
}
}