具有不同序列化器的分形变换器,用于嵌套项和集合

时间:2017-06-02 08:30:49

标签: php laravel rest thephpleague thephpleague-fractal

要更改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  
    }
}

2 个答案:

答案 0 :(得分:0)

不幸的是,我认为你要做的事情还不可能。更多信息请访问:https://github.com/thephpleague/fractal/issues/315

您仍然可以更改整个输出的序列化程序,如下所示:https://github.com/spatie/fractalistic#using-a-serializer。但这不是你想要达到的目标。

答案 1 :(得分:0)

实际上可以。 它看起来可能很冗长,但是窍门就是不使用$defaultIncludes。请使用分形助手。

class TreeTransformer extends TransformerAbstract {

    public function transform(Tree $tree) {
         return [
            'id' => (int)$tree->id,
            'name' => (string)$tree->name,
            'type' => $this->serializeType($tree)
            'branches' => $this->serializeBranches($tree)
        ];
    }

    private function serializeType(Tree $tree) {
        return fractal()
                ->serializeWith(new ArraySerializer())
                ->collection($tree->type)
                ->transformWith(TypeTransformer::class)
                ->toArray(); // ArraySerializer  
    }

    private function serializeBranches(Tree $tree) {
        return fractal()
                ->serializeWith(new DataArraySerializer())
                ->collection($tree->branches)
                ->transformWith(BranchesTransformer::class)
                ->toArray(); // DataArraySerializer  
    }
}

ArraySerializer对我有用。没尝试过DataArraySerializer