2017-06-12 117 views
0

由於Symfony 3.3的文件app/autoload.php消失了。但我用它來註冊一個自定義映射類型,如here所述。Symfony 3.3 + Doctrine/MongoDB:註冊自定義映射類型

我現在應用程序/ 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; 

如前所述hereAnnotationDriver::registerAnnotationClasses();並不需要被調用的Symfony 3.3下去了。但我不知道,哪裏放

Type::addType("MyCustomType", "Com\\MyBundle\\Db\\MyCustomTypeClass"); 

我試圖把它變成延伸BundleMyBundle類的boot()方法。但是當我應用更改後第一次執行我的單元測試時,我得到了InvalidArgumentException: Invalid type specified "MyCustomType".。當我再次執行它們時,我得到了Doctrine\ODM\MongoDB\Mapping\MappingException: Type MyCustomType already exists.

回答

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 
+0

提到我用的原則問題 - ** ** ODM(MongoDB的),而不是教義,ORM。您鏈接到Doctrine-ORM手冊。您所顯示的配置僅適用於Doctrine-ORM。 Doctrine-ODM的配置以:'doctrine_mongodb:'開頭。不幸的是,它沒有'dbal:'配置選項。 – Spunc

+1

你是絕對正確的;我的錯!你有沒有嘗試在你的'MyBundle'類文件中的'__construct()'方法中加載它? –

+0

我試着將'Type :: addType'代碼放入'__construct()'而不是'boot()'中,但它具有相同的效果。 – Spunc

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. 重新加載URL確實有效。
  5. 在這一點上,應用程序的工作原理,但重新啓動服務器再次給人以1