2012-03-18 8 views
18

Estoy intentando generar repositorios entidad y conseguir dichos mensajesDoctrina 2 - Clases No hay metadatos para procesar por ORM: generate-repositorios

Clases

No hay metadatos para procesar

que había rastreado por ese uso de

use Doctrine \ ORM \ Mapping as ORM; y @ORM \ Table no funciona correctamente.

Si cambio todo @ORM \ Table a simplemente @Table (y otras anotaciones) - comienza a funcionar, pero realmente no quiero que sea así ya que debería funcionar con la anotación @ORM.

Seguí las instrucciones de la página siguiente sin suerte. Sé que estoy cerca pero me falta algo con las rutas de archivos o los espacios de nombres. Por favor ayuda.

http://docs.doctrine-project.org/projects/doctrine-common/en/latest/reference/annotations.html

¿Alguien tenía tal problema? ¿Qué me falta?

cli-config,

use Doctrine\Common\Annotations\AnnotationReader; 
use Doctrine\Common\Annotations\AnnotationRegistry; 

require_once 'Doctrine/Common/ClassLoader.php'; 

define('APPLICATION_ENV', "development"); 
error_reporting(E_ALL); 



//AnnotationRegistry::registerFile("Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php"); 
//AnnotationRegistry::registerAutoloadNamespace("Symfony\Component\Validator\Constraint", "Doctrine/Symfony"); 
//AnnotationRegistry::registerAutoloadNamespace("Annotations", "/Users/ivv/workspaceShipipal/shipipal/codebase/application/persistent/"); 

$classLoader = new \Doctrine\Common\ClassLoader('Doctrine'); 
$classLoader->register(); 

$classLoader = new \Doctrine\Common\ClassLoader('Entities', __DIR__ . '/application/'); 
$classLoader->register(); 
$classLoader = new \Doctrine\Common\ClassLoader('Proxies', __DIR__ . '/application/persistent'); 
$classLoader->register(); 

$config = new \Doctrine\ORM\Configuration(); 
$config->setProxyDir(__DIR__ . '/application/persistent/Proxies'); 
$config->setProxyNamespace('Proxies'); 

$config->setAutoGenerateProxyClasses((APPLICATION_ENV == "development")); 


$driverImpl = $config->newDefaultAnnotationDriver(array(__DIR__ . "/application/persistent/Entities")); 
$config->setMetadataDriverImpl($driverImpl); 

if (APPLICATION_ENV == "development") { 
    $cache = new \Doctrine\Common\Cache\ArrayCache(); 
} else { 
    $cache = new \Doctrine\Common\Cache\ApcCache(); 
} 

$config->setMetadataCacheImpl($cache); 
$config->setQueryCacheImpl($cache); 


$connectionOptions = array(
    'driver' => 'pdo_mysql', 
    'host'  => '127.0.0.1', 
    'dbname' => 'mydb', 
    'user'  => 'root', 
    'password' => '' 

); 

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config); 
$platform = $em->getConnection()->getDatabasePlatform(); 
$platform->registerDoctrineTypeMapping('enum', 'string'); 

$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
    'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()), 
    'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em) 
)); 

User.php (versión de trabajo, en un principio que era como se describe, @Table era @ORM \ Mesa y otras anotaciones similar había @ORM \ parte como @ORM \ Columna etc)

<?php 
namespace Entities; 


use Doctrine\Mapping as ORM; 

/** 
* User 
* 
* @Table(name="user") 
* @Entity(repositoryClass="Repository\User") 
*/ 
class User 
{ 
    /** 
    * @var integer $id 
    * 
    * @Column(name="id", type="integer", nullable=false) 
    * @Id 
    * @GeneratedValue 
    */ 
    private $id; 

    /** 
    * @var string $userName 
    * 
    * @Column(name="userName", type="string", length=45, nullable=false) 
    */ 
    private $userName; 

    /** 
    * @var string $email 
    * 
    * @Column(name="email", type="string", length=45, nullable=false) 
    */ 
    private $email; 

    /** 
    * @var text $bio 
    * 
    * @Column(name="bio", type="text", nullable=true) 
    */ 
    private $bio; 

    public function __construct() 
    { 

    } 

} 
+0

I'm having the same issue just now. I'll post an answer if I can find a solution. – Gohn67

+0

posting the code of the entity and reader, and directory structure might help getting an accurate answer. –

+0

added sourcec code for cli config and User.php – waney

Respuesta

19

Datos 3:

si importa, estoy usando Doctrina 2.2.1. De todos modos, solo estoy agregando un poco más de información sobre este tema.

Cavé alrededor de la clase Doctrina \ configuration.php para ver cómo newDefaultAnnotationDriver creó el AnnotationDriver. El método comienza en la línea 125, pero la parte relevante es la línea 145 a 147 si está utilizando la última versión de la biblioteca común.

} else { 
    $reader = new AnnotationReader(); 
    $reader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\'); 
} 

en realidad no podía encontrar el método setDefaultAnnotationNamespace en clase AnnotationReader. Entonces eso fue raro. Pero asumo que establece el espacio de nombres Doctrine \ Orm \ Mapping, por lo que las anotaciones en ese espacio de nombres no necesitan ser prefijadas. De ahí el error ya que parece que la herramienta doctrina cli genera las entidades de manera diferente. No estoy seguro de por qué es eso.

Notarás en mi respuesta a continuación que no llamé al método setDefaultAnnotationNamespace.

Una nota al margen, me di cuenta en su clase de entidad de usuario que tiene use Doctrine\Mapping as ORM. ¿No debería el archivo generado crear use Doctrine\Orm\Mapping as ORM;?O tal vez eso es un error tipográfico.

EDITAR 1: Bien, he encontrado el problema. Aparentemente tiene que ver con el controlador de anotación predeterminado utilizado por la clase \ Doctrine \ ORM \ Configuration.

Por lo tanto, en lugar de utilizar $config->newDefaultAnnotationDriver(...), debe crear una instancia de un nuevo AnnotationReader, un nuevo AnnotationDriver y luego configurarlo en su clase de configuración.

Ejemplo:

AnnotationRegistry::registerFile("Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php"); 
$reader = new AnnotationReader(); 
$driverImpl = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader, array(__DIR__ . "/application/persistent/Entities")); 
$config->setMetadataDriverImpl($driverImpl); 

Edit2 (Aquí los ajustes agregado a su cli-config.php):

use Doctrine\Common\Annotations\AnnotationReader; 
use Doctrine\Common\Annotations\AnnotationRegistry; 

require_once 'Doctrine/Common/ClassLoader.php'; 

define('APPLICATION_ENV', "development"); 
error_reporting(E_ALL); 

$classLoader = new \Doctrine\Common\ClassLoader('Doctrine'); 
$classLoader->register(); 

$classLoader = new \Doctrine\Common\ClassLoader('Entities', __DIR__ . '/application/'); 
$classLoader->register(); 
$classLoader = new \Doctrine\Common\ClassLoader('Proxies', __DIR__ . '/application/persistent'); 
$classLoader->register(); 

$config = new \Doctrine\ORM\Configuration(); 
$config->setProxyDir(__DIR__ . '/application/persistent/Proxies'); 
$config->setProxyNamespace('Proxies'); 

$config->setAutoGenerateProxyClasses((APPLICATION_ENV == "development")); 


//Here is the part that needs to be adjusted to make allow the ORM namespace in the annotation be recognized 

#$driverImpl = $config->newDefaultAnnotationDriver(array(__DIR__ . "/application/persistent/Entities")); 

AnnotationRegistry::registerFile("Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php"); 
$reader = new AnnotationReader(); 
$driverImpl = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader, array(__DIR__ . "/application/persistent/Entities")); 
$config->setMetadataDriverImpl($driverImpl); 

//End of Changes 

if (APPLICATION_ENV == "development") { 
    $cache = new \Doctrine\Common\Cache\ArrayCache(); 
} else { 
    $cache = new \Doctrine\Common\Cache\ApcCache(); 
} 

$config->setMetadataCacheImpl($cache); 
$config->setQueryCacheImpl($cache); 


$connectionOptions = array(
    'driver' => 'pdo_mysql', 
    'host'  => '127.0.0.1', 
    'dbname' => 'mydb', 
    'user'  => 'root', 
    'password' => '' 
); 

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config); 
$platform = $em->getConnection()->getDatabasePlatform(); 
$platform->registerDoctrineTypeMapping('enum', 'string'); 

$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
    'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()), 
    'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em) 
)); 
+0

You are a life saver. I had used an old Symfony project to generate the entity mappings directly from the database tables and just copied the entity classes over to this new Doctrine project. Your answer was spot on. I did a find "@ORM\" and replace "@" on my entity classes and voila. Now I actually have entity metadata showing in the doctrine console. – Codezilla

0

no puedo encontrar ninguna referencia a @ORM\Table cualquier lugar, pero en proyectos Symfony2. En la documentación siempre se hace referencia como @Table

Sé que funciona en sf2 (lo estoy usando allí). ¿Es posible que se trate de un error con una instalación automática de Doctrine?

+0

I don't know why but the namespace is ommitted in the documentation. – undefined

+1

I think the documentation is not up to date (which is frustrating). –

0

La explicación más posible es, como dijiste, que hay algo mal con incluir (problema de espacio de nombres, problema de ruta, etc.) en el lector o en la entidad.

0

me pegó un problema similar (aunque al revés), al actualizar de Doctrine 2.0 a Doctrine 2.1 (o 2.2). Para Doctrine 2.0 mis anotaciones con @Table funcionaban bien, pero después de la actualización comenzó a quejarse de que la anotación no se había cargado. Le sugiero que da Doctrina 2,2 a ir, con el fin de utilizar @ORM \ Tabla

0

notado una pequeña discrepancia ...

En su Entidad su uso;

use Doctrine\Mapping as ORM; 

En lugar de:

use Doctrine\ORM\Mapping as ORM; 

Quizás eso solucionarlo?

1

Como dijo Gohn67 .. tienes que instanciar un nuevo lector.

Tuve el mismo problema pero con Zend. El problema está en el lector y no en el controlador.

Ex: si uso "Doctrina \ Common \ Anotaciones \ SimpleAnnotationReader" como lector de que tenía que escribir todo mi anotación sin la @ORM

Pero si yo uso "Doctrina \ Common \ Anotaciones \ AnnotationReader" i que poner @ORM en las anotaciones para conseguir trabajo

0

Mi problema fue en Bootstrap.php (requerido por cli-config.php)

$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode); 

este "src" no estaba apuntando a la carpeta fuente correcta .

0

[Inglés]

Revisión del Bootstrap.php archivo y donde se configura la doctrina ORM, cambia las anotaciones por yaml:

/* Configuring by annotacions*/ 
//$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode); 

/* Configuring by yaml*/ 
$config = Setup::createYAMLMetadataConfiguration(array(__DIR__."/config/yml"), $isDevMode); 

Nota: la ruta/config/yml debe existe.

[Espanish]

Revisar el archivo bootstrap y donde configuras el orm doctrine, cambia las anotaciones por yaml:

/* Configuring by annotacions*/ //$config = Setup::createAnnotationMetadataConfiguration(array(DIR ."/src"), $isDevMode);

/* Configuring by yaml*/ 
$config = Setup::createYAMLMetadataConfiguration(array(__DIR__."/config/yml"), $isDevMode); 

Importante: el directorio /config/yml debe existir.

8

I just ran into the same problem that you've got. I am using Doctrine 2.4. I can fix this issue by doing this in the config file. I am not sure if this works for versions < 2.3.

$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src/entities"), $isDevMode, null, null, FALSE); // just add null, null, false at the end 

Below is the documentation for the method createAnnotationMetadataConfiguration. I have just dig into the source code. By default it uses a simple annotation reader, which means you don't need to have ORM\ in front of your annotation, you can do @Entities instead of @ORM\Entities. So all you need to do here is to disable it using simple annotation reader.

/** 
* Creates a configuration with an annotation metadata driver. 
* 
* @param array $paths 
* @param boolean $isDevMode 
* @param string $proxyDir 
* @param Cache $cache 
* @param bool $useSimpleAnnotationReader 
* 
* @return Configuration 
*/ 
public static function createAnnotationMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null, $useSimpleAnnotationReader = true) 
+0

This works, thanks –

+0

this is the real life saver – NDM

0
.. 

$generator = new EntityGenerator(); 
$generator->setAnnotationPrefix(''); // edit: quick fix for No Metadata Classes to process 
$generator->setUpdateEntityIfExists(true); // only update if class already exists 
//$generator->setRegenerateEntityIfExists(true); // this will overwrite the existing classes 
$generator->setGenerateStubMethods(true); 

$generator->setAnnotationPrefix('ORM\\'); // <<---------------| 

$generator->setGenerateAnnotations(true); 
$generator->generate($metadata, __DIR__ . '/Entities'); 

.. 
Cuestiones relacionadas