V3Resource.php 1008 B

123456789101112131415161718192021222324252627282930313233
  1. <?php
  2. namespace App\Http\Resources;
  3. use Illuminate\Http\Resources\Json\JsonResource;
  4. /**
  5. * v3 资源的基类。所有 `*V3Resource` 都继承它。
  6. *
  7. * 作用是让 `XxxV3Resource::collection()` 产出 {@see V3ResourceCollection},
  8. * 从而裁掉分页里的绝对 URL。除此之外与普通 JsonResource 完全一致——
  9. * 响应形状由框架决定:
  10. *
  11. * 单个:{data: {...}}
  12. * 列表:{data: [...], meta: {...}}
  13. *
  14. * 控制器直接 `return XxxV3Resource::make($model)` 或
  15. * `return XxxV3Resource::collection($query->paginate($n))`,不需要任何 helper。
  16. *
  17. * 载荷是普通数组(不是 Eloquent 模型)时可以直接用本类:
  18. *
  19. * return V3Resource::collection($items)->additional(['meta' => [...]]);
  20. */
  21. class V3Resource extends JsonResource
  22. {
  23. /**
  24. * @param mixed $resource
  25. */
  26. protected static function newCollection($resource): V3ResourceCollection
  27. {
  28. return new V3ResourceCollection($resource, static::class);
  29. }
  30. }