aqjw / resource-typeable
扩展Laravel资源的功能,将其分离为不同类型。
1.0.0
2022-06-26 11:11 UTC
Requires
- php: ^7.3|^8.0
This package is auto-updated.
Last update: 2024-09-26 15:50:24 UTC
README
此扩展包扩展了Laravel资源,使其能够按类型分离。
安装
使用composer安装此包
composer require aqjw/resource-typeable
用法
要将资源转换为可类型化,只需使用ResourceTypeable
特质。
use Aqjw\ResourceTypeable\ResourceTypeable; ... class ProductResource extends JsonResource { use ResourceTypeable; ...
现在您的资源具有了可类型化能力。
示例
use Aqjw\ResourceTypeable\ResourceTypeable; ... class ProductResource extends JsonResource { use ResourceTypeable; /** * Tiny product resource * * @return array */ public function tiny($request): array { return [ 'id' => $this->id, 'title' => $this->title, 'slug' => $this->slug, 'price' => $this->price, ]; } /** * Full product resource * * @return array */ public function full($request): array { return array_merge( $this->tiny($request), [ 'brand' => $this->brand, 'model' => $this->model, 'material' => $this->material, 'size' => $this->size, 'tags' => $this->tags, 'color' => $this->color, 'print' => $this->print, ], ); } }
在控制器中,您可以使用资源,就像以前一样。
... class ProductController extends Controller { ... public function index() { $products = Product::paginate(9); return new ProductCollection($products); // will return tiny resource type // or return ProductCollection::make($products); // will return tiny resource type // or return ProductResource::collectionType('full', $products); // will return full resource type } ...
另一个示例
... class ProductController extends Controller { ... public function show(Product $product) { return ProductResource::makeType('full', $product); } ...
配置
默认的资源类型是tiny
,但您可以通过声明$resource_type
变量来更改它
use Aqjw\ResourceTypeable\ResourceTypeable; ... class ProductResource extends JsonResource { use ResourceTypeable; /** * Resource type * * @var string */ protected static $resource_type = 'full'; ...
提示
资源类型不受限制,您可以为其创建任何名称,而不仅仅是tiny
和full
。但请注意,它们不应该覆盖父类的方法。
许可
MIT许可(MIT)。有关更多信息,请参阅许可文件。