简体   繁体   中英

Doctrine 2: Generated entities from database don't have namespaces

I am creating entities from the database trough the \\Doctrine\\ORM\\Tools\\DisconnectedClassMetadataFactory() class. This works perfectly! Except for the namespace generation. There are no namespaces generated. I am storing my entities in App/Model/Entities .

Does anyone know how to make the generator add namespaces to the entities?

This is the code I use to generate the entities:

<?php
$em->getConfiguration()->setMetadataDriverImpl(
    new \Doctrine\ORM\Mapping\Driver\DatabaseDriver(
        $em->getConnection()->getSchemaManager()
    )
);

$cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
$cmf->setEntityManager($em);
$metadata = $cmf->getAllMetadata();

// GENERATE PHP ENTITIES!
$entityGenerator = new \Doctrine\ORM\Tools\EntityGenerator(); 
$entityGenerator->setGenerateAnnotations(true); 
$entityGenerator->setGenerateStubMethods(true); 
$entityGenerator->setRegenerateEntityIfExists(false); 
$entityGenerator->setUpdateEntityIfExists(true); 
$entityGenerator->generate($metadata, __dir__. '/Model/Entities");

I think, the better way is set namespace directly to driver

<?php
$driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager());
$driver->setNamespace('App\\Model\\Entities\\');

$em->getConfiguration()->setMetadataDriverImpl($driver);

....

I don't think you can set the namespace when importing from the database, because the EntityGenerator takes the namespace information from the metadata. The database does not have or need namespaces, so the information does not automatically come from there.

You could try looping over the $metadata object and adding the namespace yourself to class names. The code in the EntityGenerator that retrieves the namespace is quite simple:

private function _getNamespace(ClassMetadataInfo $metadata)
{
    return substr($metadata->name, 0, strrpos($metadata->name, '\\'));
}

If all else fails, you can always implement your own EntityGenerator that you can feed a namespace to use. We did that in our large project, where there are some other custom tasks to be done during generation. However, the EntityGenerator is not easily overriden, lots of private methods and properties so you probably have to copy&paste the whole thing.

You may use this PHP script to generate entities from database tables. This script adds a sample namespace to generated files, so you can set your Namespace instead. https://gist.github.com/SamvelG/3b39622844f23cac7e76#file-doctrine-entity-generator-php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM