rdarcy1 / fractal-helpers

该包已被废弃,不再维护。作者建议使用 konsulting/fractal-helpers 包。

0.5.0 2021-01-18 21:19 UTC

This package is auto-updated.

Last update: 2022-02-01 13:13:32 UTC


README

这是一个针对 Fractal 的小扩展,它使得在资源中包含关系变得容易。专为与 Laravel/Eloquent 一起使用而设计,但它也可以与任何表达相同接口以检索关系的模型或资源一起使用。

安装

composer require konsulting/fractal-helpers

用法

要使用此包,请在您的转换器中扩展 Konsulting\FractalHelpers\TransformerAbstract 而不是基本的 Fractal 转换器。

在构建使用 Fractal 的 API 时,我发现自己在 Eloquent 模型上包含关系时重复相同的代码。

// BookTransformer.php

protected $availableIncludes = [
    'author',
    'characters'
];

public function includeAuthor(Book $book) {
     return $this->item($book->author, new AuthorTransformer);
}

public function includeCharacters(Book $book) {
    return $this->collection($book->characters, new CharacterTransformer);
}

通过包含的 TransformerAbstract 类,您可以更简洁地表达上述代码:

// BookTransformer.php

protected $itemIncludes = [
    'author' => AuthorTransformer::class,
];

protected $collectionIncludes = [
    'characters' => CharacterTransformer::class,
];

空关系

如果关系返回 null,它将自动转换为 League\Fractal\Resource\NullResource 对象,而不是传递到该关系的关联转换器。这意味着在每个转换器中不需要检查 null。