我正在为Symfony2编写一个库+包。我的模型在库中(TNTExpress\Model
),我的学说映射在包中(winzou\Bundle\TNTExpressBundle
)。
我很难弄清楚CompilerPass的一个问题,告诉Doctrine我的映射模型不在我的包中。我刚跟着http://symfony.com/doc/current/cookbook/doctrine/mapping_model_classes.html
我的问题是,Doctrine仍然在捆绑中寻找我的模型:
[Doctrine\Common\Persistence\Mapping\MappingException]
Class 'winzou\Bundle\TNTExpressBundle\Entity\Expedition' does not exist
这是我的编译器类的bundle类,名为:
namespace winzou\Bundle\TNTExpressBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
class winzouTNTExpressBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
$container->addCompilerPass(DoctrineOrmMappingsPass::createXmlMappingDriver(
array($this->getConfigFilesPath() => $this->getModelNamespace())
));
}
protected function getConfigFilesPath()
{
return sprintf(
'%s/Resources/config/doctrine',
$this->getPath()
);
}
protected function getModelNamespace()
{
return 'TNTExpress\Model';
}
}
我的映射位于@winzouTNTExpressBundle/Resources/config/doctrine/Expedition.orm.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping">
<entity name="TNTExpress\Model\Expedition" table="winzou_tntexpress_expedition">
<id name="id" type="integer">
<generator strategy="AUTO" />
</id>
<field name="parcelResponses" column="parcel_responses" type="object" />
<field name="PDFLabels" column="pdf_labels" type="text" />
<field name="pickUpNumber" column="pickup_number" type="string" nullable="true" />
</entity>
</doctrine-mapping>
我可以在appDevDebugProjectContainer.php的getDoctrine_Orm_DefaultEntityManagerService方法中看到,两个名称空间都是为我的模型命名空间定义的:
protected function getDoctrine_Orm_DefaultEntityManagerService()
{
// Good config path, wrong namespace (inside the bundle)
$c = new \Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver(array('...', 'D:\\www\\TNTExpressBundle\\Resources\\config\\doctrine' => 'winzou\\Bundle\\TNTExpressBundle\\Entity'));
$c->setGlobalBasename('mapping');
$d = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
// ...
$d->addDriver($c, 'winzou\\Bundle\\TNTExpressBundle\\Entity');
// ...
// Good config path, good namespace (inside the library)
$d->addDriver(new \Doctrine\ORM\Mapping\Driver\XmlDriver(new \Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator(array('D:\\www\\TNTExpressBundle/Resources/config/doctrine' => 'TNTExpress\\Model'), '.orm.xml')), 'TNTExpress\\Model');
$e = new \Doctrine\ORM\Configuration();
$e->setEntityNamespaces(array('...', 'winzouTNTExpressBundle' => 'winzou\\Bundle\\TNTExpressBundle\\Entity'));
// ...
}
最后,如果我通过在这个MappingDriverChain::addDriver($c)
方法中几乎没有使用if来避免调用addDriver
,那么一切正常。
我的问题是:如何避免在MappingDriverChain上调用这个错误的命名空间? 我使用CompilerPass做错了吗?我只是按照这里的文档......
谢谢!