在Symfony中如何实现Doctrine自定义类注解的继承?
问题结论
Doctrine 提供的默认 Annotation Reader 的 getClassAnnotation() 方法仅读取当前类直接声明的注解,不会自动递归检索父类的注解,这是官方的预期设计,不是你的实现问题。
解决方法
你可以任选以下两种方案实现父类注解的继承读取:
方案1:为自定义注解添加@Inherited元注解
Doctrine 的注解系统支持@Inherited元注解,标记后 Reader 会自动从当前类的继承链中查找对应注解,修改你的注解定义即可:
use Doctrine\Common\Annotations\Annotation; /** * @Annotation * @Target("CLASS") * @Inherited // 新增这一行 */ final class TimestampAware { }
注意:该特性仅对类级别的注解生效,方法/属性级别的注解无法通过该方式继承。
方案2:手动递归遍历父类读取注解
如果需要兼容更复杂的场景(比如多重继承、特性注解读取),可以修改监听器中的注解读取逻辑,手动遍历当前类的所有父类查找注解:
修改onPersistOrUpdate方法的注解读取部分:
protected function onPersistOrUpdate(LifecycleEventArgs $args) { $this->logger->info("Reader: ".get_class($this->reader)); $entity = $args->getEntity(); $reflection = new \ReflectionClass($entity); $timestampAware = null; // 遍历当前类及所有父类查找注解 while ($reflection && !$timestampAware) { $timestampAware = $this->reader->getClassAnnotation( $reflection, TimestampAware::class ); $reflection = $reflection->getParentClass(); } if (!$timestampAware) { return; } // update timestamp... }
该方案兼容性更强,不需要依赖注解的@Inherited标记,也支持自定义继承链的查找逻辑。
内容的提问来源于stack exchange,提问作者FLichter
相关产品推荐
相关产品推荐

