You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Doctrine代理类中检测父类的PHP8 #[Auditable]属性?

解决Doctrine Proxy实体的PHP8属性检测问题

问题核心是Doctrine生成的Proxy类是原始实体的子类,而你要检测的#[Auditable]属性定义在父类(原始实体)上,直接反射Proxy类无法获取到父类的属性。可以通过Doctrine自身的Proxy机制来获取原始实体类,从而正确检测属性。

修改你的getAttribute方法如下:

use Doctrine\Persistence\Proxy;

public function getAttribute($entity, string $attributeClass): mixed
{
    if (!is_object($entity)) {
        return null;
    }

    // 处理Doctrine Proxy实体,获取原始实体类
    if ($entity instanceof Proxy) {
        $className = $entity->getClassName();
        $reflectionClass = new ReflectionClass($className);
    } else {
        $reflectionClass = new ReflectionClass($entity);
    }

    $reflectionAttr = $reflectionClass->getAttributes($attributeClass)[0] ?? null;

    return $reflectionAttr ? $reflectionAttr->newInstance() : null;
}

说明

  • Doctrine的Proxy类都实现了Doctrine\Persistence\Proxy接口,该接口提供了getClassName()方法,直接返回原始实体的完整类名,无需手动解析父类。
  • 这种方式完全适配Doctrine的机制,不需要预加载实体,也不用改用接口,保持代码简洁性。
  • 确保你的项目中已经引入了doctrine/persistence组件(Symfony项目通常默认包含)。

内容的提问来源于stack exchange,提问作者kachnitel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 13:35:05