mmmmm
mmmmm

Reputation: 605

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");

Upvotes: 5

Views: 3587

Answers (3)

Samvel Gevorgyan
Samvel Gevorgyan

Reputation: 1

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

Upvotes: -3

leninzprahy
leninzprahy

Reputation: 4803

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);

....

Upvotes: 9

YetiCGN
YetiCGN

Reputation: 833

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.

Upvotes: 4

Related Questions