自Symfony 3.3以来,文件 app / autoload.php 消失了。但是我用它来注册here所描述的自定义映射类型。
我当前的 app / autoload.php 如下所示:
use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
use Doctrine\ODM\MongoDB\Types\Type;
/** @var ClassLoader $loader */
$loader = require __DIR__.'/../vendor/autoload.php';
Type::addType("MyCustomType", "Com\\MyBundle\\Db\\MyCustomTypeClass");
AnnotationRegistry::registerLoader([$loader, 'loadClass']);
AnnotationDriver::registerAnnotationClasses();
return $loader;
如上所述here,使用Symfony 3.3不再需要调用AnnotationDriver::registerAnnotationClasses();
。但我不知道,在哪里放
Type::addType("MyCustomType", "Com\\MyBundle\\Db\\MyCustomTypeClass");
我尝试将其放入boot()
类的MyBundle
方法,该方法扩展了Bundle
。但是当我在应用更改后第一次执行单元测试时,我得到InvalidArgumentException: Invalid type specified "MyCustomType".
。当我再次执行它们时,我得到Doctrine\ODM\MongoDB\Mapping\MappingException: Type MyCustomType already exists.
。
答案 0 :(得分:0)
正如官方文档中所述:http://symfony.com/doc/current/doctrine/dbal.html#registering-custom-mapping-types
# app/config/config.yml
doctrine:
dbal:
types:
my_custom_type: Com\\MyBundle\\Db\\MyCustomTypeClass
答案 1 :(得分:0)
我找到了解决问题的解决方案here。虽然这个解决方案适用于Doctrine-ORM,但它也适用于Doctrine-ODM(Doctrine / MongoDB)。
它使用我首先尝试的相同方法:将Type::addType
调用放入Bundle类的boot()
方法。但是,它首先检查类型是否已存在:
public function boot() {
if(!Type::hasType("MyCustomType")) {
Type::addType("MyCustomType", "Com\\MyBundle\\Db\\MyCustomTypeClass");
}
}
虽然我不确定,但是这是最优雅的解决方案。
修改强>
虽然它似乎工作(单元测试正在运行)但它不能在服务器上运行。它似乎与Hydrators有关。
bin/console server:run
会出错:Uncaught InvalidArgumentException: Invalid type specified "MyCustomType"
(1/1) InvalidArgumentException Invalid type specified "MyCustomType".
(现在显示在浏览器中)。