Doctrine 2: Created objects from the database do not have namespaces

I create entities from a database through the class \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory() . It works great! Except namespace generation. Created namespaces do not exist. I save my objects in App/Model/Entities .

Does anyone know how to get a generator to add namespaces to objects?

This is the code I use to create 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"); 
+4
source share
3 answers

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

You can try to loop over the $ metadata object and add a namespace to the class names. The code in EntityGenerator that retrieves the namespace is pretty 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 so that you can use the namespace to use. We did this in our large project, where other user tasks are performed during the generation process. However, EntityGenerator is not easy to overestimate, many private methods and properties, so you may have to copy and paste all of this.

+4
source

I think the best way is to set the namespace directly in the driver

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

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

-3
source

Source: https://habr.com/ru/post/1436354/


All Articles