API Platform Laravel版:如何区分条目与集合路由的暴露属性?
解决方案
API Platform Laravel版本完全支持类似Symfony版的normalizationContext机制,无需额外DTO或自定义Provider即可实现集合与条目路由的属性区分,具体步骤如下:
1. 为模型属性标记序列化分组
在Eloquent模型的属性上,通过#[ApiProperty]注解指定该属性所属的序列化分组,比如区分collection(集合路由用)和item(条目路由用):
use ApiPlatform\Metadata\ApiProperty; use Illuminate\Database\Eloquent\Model; class Post extends Model { // 集合和条目路由都显示的属性 #[ApiProperty(groups: ['collection', 'item'])] public $id; #[ApiProperty(groups: ['collection', 'item'])] public $title; // 仅条目路由显示的属性 #[ApiProperty(groups: ['item'])] public $content; #[ApiProperty(groups: ['item'])] public $created_at; }
2. 为资源操作配置序列化上下文
在资源的操作定义中,为集合操作(GetCollection)和条目操作(Get)分别指定对应的normalizationContext,绑定对应的分组:
use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\Get; use ApiPlatform\Metadata\GetCollection; #[ApiResource( operations: [ // 条目路由:仅显示item分组的属性 new Get(normalizationContext: ['groups' => ['item']]), // 集合路由:仅显示collection分组的属性 new GetCollection(normalizationContext: ['groups' => ['collection']]) ] )] class Post extends Model { // ... 模型属性及逻辑 }
如果习惯用配置文件管理资源(config/api_platform/resources.php),也可以这样配置:
return [ App\Models\Post::class => [ 'operations' => [ 'get' => [ 'normalization_context' => ['groups' => ['item']], ], 'get_collection' => [ 'normalization_context' => ['groups' => ['collection']], ], ], ], ];
原理说明
这种方式利用API Platform内置的序列化分组机制,在序列化阶段根据操作对应的上下文过滤属性,完全避开了你之前遇到的Provider时机问题,也不需要额外自定义分页器,Hydra相关属性会正常生成,不会出现混乱。
内容的提问来源于stack exchange,提问作者Philippe CARLE
相关产品推荐
相关产品推荐

