升级doctrine/orm至2.16.2后遇AttributeDriver弃用通知,未找到配置选项
Doctrine ORM 2.16.2升级后AttributeDriver废弃警告的解决方法
升级到Doctrine ORM 2.16.2后出现的这个废弃警告,是提示ORM 3.0会改变AttributeDriver的字段报告逻辑,要求提前开启新模式,但这个参数没有直接的配置项,得通过以下方式设置:
如果你用的是Symfony项目
因为Symfony默认通过容器管理Doctrine服务,需要自定义编译器Pass来修改AttributeDriver的构造参数:
- 创建编译器Pass类
在项目的src/DependencyInjection/Compiler目录下新建DoctrineAttributeDriverCompilerPass.php文件,内容如下:
// src/DependencyInjection/Compiler/DoctrineAttributeDriverCompilerPass.php namespace App\DependencyInjection\Compiler; use Doctrine\ORM\Mapping\Driver\AttributeDriver; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class DoctrineAttributeDriverCompilerPass implements CompilerPassInterface { public function process(ContainerBuilder $container): void { foreach ($container->findTaggedServiceIds('doctrine.orm.metadata_driver') as $id => $tags) { $definition = $container->getDefinition($id); if ($definition->getClass() === AttributeDriver::class) { // 修改构造参数中的第三个值为true $arguments = $definition->getArguments(); $arguments[2] = true; $definition->setArguments($arguments); } } } }
- 注册编译器Pass
打开项目的src/Kernel.php,在build方法中添加这个Pass的注册:
// src/Kernel.php namespace App; use App\DependencyInjection\Compiler\DoctrineAttributeDriverCompilerPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel as BaseKernel; class Kernel extends BaseKernel { // 保留原有方法,新增或修改build方法 protected function build(ContainerBuilder $container): void { $container->addCompilerPass(new DoctrineAttributeDriverCompilerPass()); } }
如果你用的是普通PHP项目
直接实例化AttributeDriver时,把第三个构造参数设为true即可:
$driver = new \Doctrine\ORM\Mapping\Driver\AttributeDriver( ['/path/to/your/entities'], // 你的实体文件所在路径 null, // 可选的ClassMetadataFactory实例,不需要就传null true // 开启reportFieldsWhereDeclared模式 );
开启这个模式后,ORM会严格报告字段声明的位置,能帮你提前发现无效的映射配置(比如子类重复声明父类已有的字段),避免升级到ORM 3.0时出现兼容性问题。
内容的提问来源于stack exchange,提问作者Abderrahim
相关产品推荐
相关产品推荐

