自定义StateProvider时,如何配置JsonLd的@context等属性?
问题解决思路及方案
核心问题分析
自定义StateProvider返回的对象未触发API Platform的自动路由生成、上下文关联和类型映射逻辑——默认的Doctrine集成会自动处理这些元数据,但自定义Provider需要显式配置才能让系统识别并生成符合预期的JSON-LD格式。
解决方案步骤
显式配置API资源的路由与操作
必须在#[ApiResource]中明确指定GET操作的uriTemplate,并关联标识符变量,让系统能基于实体的id生成正确的@id,同时指定@context路径:#[ApiResource( types: 'https://schema.org/UpdateAction', provider: TransitionStateProvider::class, operations: [ new Get( uriTemplate: '/transitions/{id}', uriVariables: [ 'id' => new UriVariable( fromClass: Transition::class, identifier: true ) ] ) ], context: '/contexts/Transition' )] class Transition { #[ApiProperty( identifier: true, types: ['https://schema.org/identifier'], )] public int $id; }修正StateProvider的逻辑
不要硬编码id值,而是使用请求传入的uriVariables中的id,确保返回的对象与请求路径匹配:class TransitionStateProvider implements ProviderInterface { public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null { $transition = new Transition(); $transition->id = $uriVariables['id']; return $transition; } }确保@type正确映射
已设置的types属性https://schema.org/UpdateAction会被序列化器优先使用,若仍不生效,可在实体类上补充#[ApiProperty(type: 'https://schema.org/UpdateAction')]来强制指定类型。
关键说明
- 关联Doctrine的资源正常,是因为Doctrine的
StateProvider会自动从实体元数据和路由配置中推导@id、@context和@type; - 自定义Provider需要显式配置操作的路由模板和上下文,否则系统会默认生成临时
@id(.well-known/genid/...)和默认上下文; context参数直接指定@context的返回值,需与系统自动生成的上下文路径保持一致。
内容的提问来源于stack exchange,提问作者Alexandre Tranchant
相关产品推荐
相关产品推荐

