Symfony 3.3 + Doctrine / MongoDB:注册自定义映射类型

时间:2017-06-12 20:39:45

标签: php mongodb symfony doctrine doctrine-odm

自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.

2 个答案:

答案 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有关。

  1. 第一次调用bin/console server:run会出错:Uncaught InvalidArgumentException: Invalid type specified "MyCustomType"
  2. 终止服务器后,重启服务器 工作。
  3. 但是,浏览到映射到控制器的任何URL都会再次显示(1/1) InvalidArgumentException Invalid type specified "MyCustomType".(现在显示在浏览器中)。
  4. 重新加载网址确实有用。
  5. 此时,应用程序正常运行,但重新启动服务器会再次出现1中提到的问题。