如何在Trait中结合API Platform序列化组使用Timestampable
API Platform 公共时间字段Trait复用解决方案
你可以通过以下两种主流方案实现需求,可根据业务场景选择:
方案1:公共序列化组统一管理(推荐大部分场景使用)
在Trait中定义通用的公共序列化组,所有引入该Trait的实体在归一化配置中追加该公共组即可自动带出时间字段:
通用Trait代码
<?php namespace App\Trait; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use Symfony\Component\Serializer\Annotation\Groups; trait TimestampableCreatedAtTrait { #[ORM\Column(type: 'datetime')] #[Groups(['timestamp:output'])] /** * @Gedmo\Timestampable(on="create") */ private \DateTime $createdAt; public function getCreatedAt(): \DateTime { return $this->createdAt; } }
实体引入示例
<?php namespace App\Entity; use ApiPlatform\Metadata\ApiResource; use App\Trait\TimestampableCreatedAtTrait; #[ApiResource( normalizationContext: [ 'groups' => ['article_category:output', 'timestamp:output'] ] )] class ArticleCategory { use TimestampableCreatedAtTrait; // 实体其他业务属性、逻辑 }
- 优势:配置简单易维护,后续新增
updatedAt等公共字段只需修改Trait即可全局生效,无需调整每个实体的配置。
方案2:实体级单独配置(适合个性化规则场景)
如果不需要全局公共组,可直接在实体的API资源配置中为createdAt字段单独绑定当前实体的专属序列化组,无需修改Trait代码:
通用Trait代码
<?php namespace App\Trait; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; trait TimestampableCreatedAtTrait { #[ORM\Column(type: 'datetime')] /** * @Gedmo\Timestampable(on="create") */ private \DateTime $createdAt; public function getCreatedAt(): \DateTime { return $this->createdAt; } }
实体配置示例
<?php namespace App\Entity; use ApiPlatform\Metadata\ApiResource; use App\Trait\TimestampableCreatedAtTrait; #[ApiResource( normalizationContext: [ 'groups' => ['article_category:output'] ], // 为Trait提供的createdAt属性绑定当前实体专属序列化组 properties: [ 'createdAt' => [ 'groups' => ['article_category:output'] ] ] )] class ArticleCategory { use TimestampableCreatedAtTrait; // 实体其他业务属性、逻辑 }
- 优势:完全兼容现有实体的序列化组规则,无需改动原有业务的归一化配置,适合不同实体序列化规则差异较大的场景。
内容的提问来源于stack exchange,提问作者mcwnuq
相关产品推荐
相关产品推荐

