Example #1
0
 /**
  * a partir de la base de datos, nos genera las entidades
  */
 public function importarEntidadesDeBD()
 {
     //obtenemos las instancias de los metadatos
     $this->em->getConfiguration()->setMetadataDriverImpl(new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($this->em->getConnection()->getSchemaManager()));
     $cmf = new Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($this->em);
     $metadata = $cmf->getAllMetadata();
     //exporta a un formato dado como xml,yml o php, entity (no entidades) a la carpeta destino
     $cme = new \Doctrine\ORM\Tools\Export\ClassMetadataExporter();
     $exporter = $cme->getExporter('xml', APPPATH . 'models/php');
     $exporter->setMetadata($metadata);
     $exporter->export();
 }
Example #2
0
 protected function _getMetadata()
 {
     if (null === $this->metadata) {
         $this->bootstrap->bootstrap('Doctrine2');
         $em = $this->bootstrap->getResource('Doctrine2');
         $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory($em);
         $metadatas = $cmf->getAllMetadata();
         $entityName = $this->_getEntityName();
         $entityClass = $this->_getModuleNamespace() . '_Model_' . $entityName;
         $metadata = current(\Doctrine\ORM\Tools\Console\MetadataFilter::filter($metadatas, $entityClass));
         $this->metadata = $metadata;
     }
     return $this->metadata;
 }
Example #3
0
 /**
  * generate entity objects automatically from mysql db tables
  * @return none
  */
 function generate_classes()
 {
     $this->em->getConfiguration()->setMetadataDriverImpl(new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($this->em->getConnection()->getSchemaManager()));
     $platform = $this->em->getConnection()->getDatabasePlatform();
     $platform->registerDoctrineTypeMapping('enum', 'string');
     $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($this->em);
     $metadata = $cmf->getAllMetadata();
     $generator = new \Doctrine\ORM\Tools\EntityGenerator();
     $generator->setUpdateEntityIfExists(true);
     $generator->setGenerateStubMethods(true);
     $generator->setGenerateAnnotations(true);
     $generator->generate($metadata, APPPATH . "models/Entities");
 }
Example #4
0
 public function checkEntities($force = false)
 {
     if (!is_dir($this->entityFolder . 'Entity') || $force) {
         $this->prepareFolder($force);
         $this->configure();
         // custom datatypes (not mapped for reverse engineering)
         $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
         $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
         $driver = new RestDriver($this->em->getConnection()->getSchemaManager());
         $driver->setNamespace($this->namespace);
         $driver->setBiDirecionalEntities(true);
         $this->em->getConfiguration()->setMetadataDriverImpl($driver);
         $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory($this->em);
         $cmf->setEntityManager($this->em);
         $metadata = $cmf->getAllMetadata();
         $this->EntityGenerator($metadata);
     }
     $autoLoader = new \Zend\Loader\StandardAutoloader(array('namespaces' => array('Entity' => $this->entityFolder . DIRECTORY_SEPARATOR . $this->namespace), 'fallback_autoloader' => true));
     $autoLoader->register();
 }
Example #5
0
 /**
  * Secret function, to create/update database schema from doctrine entities
  * @param type $mode
  * @return type
  */
 function db_schema($mode = "update")
 {
     try {
         $this->em = $this->doctrine->em;
         $tool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
         $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
         $cmf->setEntityManager($this->em);
         $metadata = $cmf->getAllMetadata();
         if ($mode == "create") {
             $queries = $tool->getCreateSchemaSql($metadata);
         } else {
             $queries = $tool->getUpdateSchemaSql($metadata);
         }
         echo "Total queries: " . count($queries) . "<br /><br />";
         for ($i = 0; $i < count($queries); $i++) {
             $this->db->query($queries[$i]);
             echo $queries[$i] . "<br /><br />Execution Successfull: " . ($i + 1) . "<br /><br />";
         }
     } catch (Exception $err) {
         log_message("error", $err->getMessage());
         return show_error($err->getMessage());
     }
 }
Example #6
0
include __DIR__ . '/vendor/autoload.php';
$classLoader = new \Doctrine\Common\ClassLoader('Entities', __DIR__);
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader('Proxies', __DIR__);
$classLoader->register();
// config
$config = new \Doctrine\ORM\Configuration();
$config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(__DIR__ . '/app/src/Entity'));
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
$config->setProxyDir(__DIR__ . '/Proxies');
$config->setProxyNamespace('Proxies');
$connectionParams = array('driver' => 'pdo_mysql', 'host' => '127.0.0.1', 'port' => '3306', 'user' => 'root', 'password' => 'password', 'dbname' => 'project_directory', 'charset' => 'utf8mb4');
$em = \Doctrine\ORM\EntityManager::create($connectionParams, $config);
// custom datatypes (not mapped for reverse engineering)
$em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
$em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
// fetch metadata
$driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager());
$em->getConfiguration()->setMetadataDriverImpl($driver);
$cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory($em);
$cmf->setEntityManager($em);
$classes = $driver->getAllClassNames();
$metadata = $cmf->getAllMetadata();
$generator = new Doctrine\ORM\Tools\EntityGenerator();
$generator->setUpdateEntityIfExists(true);
$generator->setGenerateStubMethods(true);
$generator->setGenerateAnnotations(true);
$generator->generate($metadata, __DIR__ . '/app/src/Entity');
print '-------------------------------------------' . PHP_EOL;
print ' Done! Generated models to `app\\src\\Entity`' . PHP_EOL;
print '-------------------------------------------' . PHP_EOL;
Example #7
0
 /**
  * Tenta estabelecer a conexão ao banco relacional ou de documentos.
  * 
  * @return \Doctrine\ORM\EntityManager | \Doctrine\ODM\MongoDB\DocumentManager
  */
 private function estabelecerConexao()
 {
     $tipo = explode(':', $this->_configuracao->get($this->_servidor . '.persistencia_uri'));
     $tipo = $tipo[0];
     if (!empty($tipo)) {
         if ($tipo === 'mongodb') {
             \Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver::registerAnnotationClasses();
         }
         $classLoader = new ClassLoader('Domain\\Entity', implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'app', 'models']));
         $classLoader->register();
         $doctrine_models_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'app', 'models']);
         $doctrine_entities_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'app', 'models', 'Domain', 'Entity']);
         $doctrine_proxies_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'tmp', 'models', 'Domain', 'Entity', 'Proxies']);
         $doctrine_hydrators_dir = implode(DIRECTORY_SEPARATOR, [__APPDIR__, 'tmp', 'models', 'Domain', 'Entity', 'Hydrators']);
         // cria os diretórios dos proxys e hydrators, caso não haja (necessários
         // para o Doctrine)
         if (!PROJECT_STAGE) {
             Arquivo::criarDiretorio($doctrine_proxies_dir);
             Arquivo::criarDiretorio($doctrine_hydrators_dir);
         }
         // verifica se não é MongoDB
         if ($tipo !== 'mongodb') {
             // provê algumas informações iniciais do banco de dados
             switch ($tipo) {
                 case 'sqlite':
                     $parametrosConexao = ['driver' => 'pdo_' . $tipo, 'path' => $this->_configuracao->get($this->_servidor . '.persistencia_banco')];
                     break;
                 case 'mysql':
                     $parametrosConexao = ['driver' => 'pdo_' . $tipo, 'user' => $this->_configuracao->get($this->_servidor . '.persistencia_usuario'), 'password' => $this->_configuracao->get($this->_servidor . '.persistencia_senha'), 'host' => $this->_configuracao->get($this->_servidor . '.persistencia_servidor'), 'dbname' => $this->_configuracao->get($this->_servidor . '.persistencia_banco'), \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET CHARACTER SET \'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET character_set_connection=\'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET character_set_client=\'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\'; SET character_set_results=\'' . $this->_configuracao->get($this->_servidor . '.persistencia_charset') . '\';'];
                     break;
                     // em teste funciona para quase todos os tipos de PDO
                 // em teste funciona para quase todos os tipos de PDO
                 default:
                     $parametrosConexao = ['driver' => 'pdo_' . $tipo, 'user' => $this->_configuracao->get($this->_servidor . '.persistencia_usuario'), 'password' => $this->_configuracao->get($this->_servidor . '.persistencia_senha'), 'host' => $this->_configuracao->get($this->_servidor . '.persistencia_servidor'), 'dbname' => $this->_configuracao->get($this->_servidor . '.persistencia_banco')];
                     break;
             }
             // cria os mapeamentos das entidades do banco de dados, caso não existam
             if (count(glob($doctrine_entities_dir . '/*.php')) === 0) {
                 $configuracao = new \Doctrine\ORM\Configuration();
                 $configuracao->setMetadataDriverImpl($configuracao->newDefaultAnnotationDriver($doctrine_entities_dir, FALSE));
                 $configuracao->setProxyDir($doctrine_proxies_dir);
                 $configuracao->setProxyNamespace('Proxies');
                 $entityManager = \Doctrine\ORM\EntityManager::create($parametrosConexao, $configuracao);
                 // custom datatypes (not mapped for reverse engineering)
                 $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
                 $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
                 // define namespace
                 $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($entityManager->getConnection()->getSchemaManager());
                 $driver->setNamespace('Domain\\Entity\\');
                 // define driver with namespace
                 $entityManager->getConfiguration()->setMetadataDriverImpl($driver);
                 $disconnectedClassMetadataFactory = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
                 $disconnectedClassMetadataFactory->setEntityManager($entityManager);
                 $entityGenerator = new \Doctrine\ORM\Tools\EntityGenerator();
                 $entityGenerator->setUpdateEntityIfExists(true);
                 $entityGenerator->setGenerateStubMethods(true);
                 $entityGenerator->setGenerateAnnotations(true);
                 $entityGenerator->generate($disconnectedClassMetadataFactory->getAllMetadata(), $doctrine_models_dir);
             }
             // carrega as entidades
             \Pudim\Arquivo::requererDiretorio($doctrine_entities_dir);
             $configuracao = \Doctrine\ORM\Tools\Setup::createConfiguration(!(bool) PROJECT_STAGE);
             $driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver(new \Doctrine\Common\Annotations\AnnotationReader(), $doctrine_entities_dir);
             // registering noop annotation autoloader - allow all annotations by default
             \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists');
             $configuracao->setMetadataDriverImpl($driver);
             $configuracao->setAutoGenerateProxyClasses(!(bool) PROJECT_STAGE);
             $configuracao->setProxyDir($doctrine_proxies_dir);
             $configuracao->setProxyNamespace('Proxies');
             if (PROJECT_STAGE) {
                 $cache = new \Doctrine\Common\Cache\ArrayCache();
             } else {
                 $cache = new \Doctrine\Common\Cache\ApcCache();
             }
             $configuracao->setMetadataCacheImpl($cache);
             $configuracao->setQueryCacheImpl($cache);
             // obtaining the entity manager (7)
             $eventManager = new \Doctrine\Common\EventManager();
             $conexao = \Doctrine\ORM\EntityManager::create($parametrosConexao, $configuracao, $eventManager);
         } else {
             $configuracao = new \Doctrine\ODM\MongoDB\Configuration();
             $metadata = AnnotationDriver::create($doctrine_entities_dir);
             $configuracao->setMetadataDriverImpl($metadata);
             $configuracao->setAutoGenerateProxyClasses(!(bool) PROJECT_STAGE);
             $configuracao->setProxyDir($doctrine_proxies_dir);
             $configuracao->setProxyNamespace('Proxies');
             $configuracao->setAutoGenerateHydratorClasses(!(bool) PROJECT_STAGE);
             $configuracao->setHydratorDir($doctrine_hydrators_dir);
             $configuracao->setHydratorNamespace('Hydrators');
             $configuracao->setDefaultDB($this->_configuracao->get($this->_servidor . '.persistencia_banco'));
             //$configuracao->setLoggerCallable(function (array $log) { print_r($log); });
             $cache_uri = $this->_configuracao->get($this->_servidor . '.cache_uri');
             if (PROJECT_STAGE && class_exists('Redis') && $cache_uri) {
                 // trata o $cache_uri pois somente precisamos do servidor e a porta
                 if (strpos($cache_uri, '//')) {
                     $cache_uri_parts = explode('//', $cache_uri);
                     if (strpos($cache_uri_parts[1], ':')) {
                         list($cache_server, $cache_port) = explode(':', $cache_uri_parts[1]);
                     } else {
                         $cache_server = $cache_uri_parts[1];
                         $cache_port = '6379';
                     }
                     unset($cache_uri_parts);
                 } else {
                     $cache_server = $cache_uri;
                     $cache_port = '6379';
                 }
                 $redis = new \Redis();
                 $redis->pconnect($cache_server, $cache_port);
                 $metadataCache = new \Doctrine\Common\Cache\RedisCache();
                 $metadataCache->setRedis($redis);
                 $configuracao->setMetadataCacheImpl($metadataCache);
                 unset($cache_server, $cache_port, $redis, $metadataCache);
             }
             $conexao = new \Doctrine\MongoDB\Connection($this->_configuracao->get($this->_servidor . '.persistencia_uri'));
             $conexao = \Doctrine\ODM\MongoDB\DocumentManager::create($conexao, $configuracao);
             // FIX: Muito importante pois força a criação dos índices no aplicativo
             $conexao->getSchemaManager()->ensureIndexes();
         }
     }
     return $conexao;
 }
Example #8
0
 public function generate_entities()
 {
     // custom datatypes (not mapped for reverse engineering)
     $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
     $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
     $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('blob', 'string');
     // fetch metadata
     $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($this->em->getConnection()->getSchemaManager());
     $driver->setNamespace('models\\Entities\\');
     //set driver implementation
     $this->em->getConfiguration()->setMetadataDriverImpl($driver);
     $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory($this->em);
     $cmf->setEntityManager($this->em);
     $classes = $driver->getAllClassNames();
     //get class metadata
     $metadata = $cmf->getAllMetadata();
     $generator = new \Doctrine\ORM\Tools\EntityGenerator();
     $generator->setGenerateAnnotations(TRUE);
     $generator->setGenerateStubMethods(TRUE);
     $generator->setRegenerateEntityIfExists(TRUE);
     $generator->setUpdateEntityIfExists(TRUE);
     $generator->setBackupExisting(FALSE);
     try {
         $generator->generate($metadata, APPPATH . 'models/Entities');
         print 'Done!';
     } catch (exception $ex) {
         die($ex->getMessage());
     }
 }
Example #9
0
 /**
  * Reverse engineering of the model from the database structure.
  * Write result to the entity folder
  * 
  * WARNING THIS WILL OVERWRITE EXISTING MODEL.
  * 
  * @return boolean 
  */
 public function generate_model()
 {
     if (!$this->is_dev()) {
         return false;
     }
     $root = $this->get_entity_path();
     $connection_parameters = $this->get_connection_parameters();
     $connection = Doctrine\DBAL\DriverManager::getConnection($connection_parameters);
     $platform = $connection->getDatabasePlatform();
     $platform->registerDoctrineTypeMapping('enum', 'string');
     $platform->registerDoctrineTypeMapping('set', 'string');
     $config = Setup::createConfiguration($this->is_dev());
     $config->setMetadataDriverImpl(new Doctrine\ORM\Mapping\Driver\DatabaseDriver(new Doctrine\DBAL\Schema\MySqlSchemaManager($connection)));
     $em = EntityManager::create($connection, $config);
     $cmf = new Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     $metadatas = $cmf->getAllMetadata();
     $repo_factory = new EntityRepositoryGenerator();
     $course = null;
     foreach ($metadatas as $metadata) {
         $n = strtolower($metadata->name);
         if ($n == 'course') {
             $course = $metadata;
             break;
         }
     }
     foreach ($metadatas as $metadata) {
         echo sprintf('Processing entity "<info>%s</info>"', $metadata->name) . '<br/>';
         foreach ($metadata->identifier as $key => $value) {
             //$mapping = $metadata->fieldMappings[$value];
             $metadata->identifier[$key] = Inflector::tableize($value);
         }
         $fields = array();
         foreach ($metadata->fieldMappings as $fieldMapping) {
             $name = Inflector::tableize($fieldMapping['fieldName']);
             $fieldMapping['fieldName'] = $name;
             $fields[$name] = $fieldMapping;
         }
         $metadata->fieldMappings = $fields;
         $n = $metadata->name;
         if ($n == 'CDocument') {
             $i = 1;
         }
         $name = $metadata->name;
         $name = Inflector::tableize($name);
         $is_course_table = strpos($name, 'c_') === 0;
         if ($is_course_table) {
             $name = substr($name, 2, strlen($name) - 2);
         }
         //$metadata->namespace = 'Entity';
         $metadata->customRepositoryClassName = 'Entity\\Repository\\' . Inflector::classify($name) . 'Repository';
         //if(is_course_table){
         $metadata->name = 'Entity\\' . Inflector::classify($name);
         $metadata->lifecycleCallbacks['prePersist'] = array('before_save');
         //}
         //$metadata->rootEntityName = Inflector::classify($name);
         if ($is_course_table) {
             foreach ($metadata->fieldMappings as $mapping) {
                 $name = $mapping['columnName'];
                 $is_id = isset($mapping['id']) ? $mapping['id'] : false;
                 if ($name != 'c_id' && $is_id) {
                 }
             }
         }
         if ($is_course_table) {
             $metadata->is_course_table = true;
             //                $mapping = array();
             //                $mapping['cascade'] = array();
             //                $mapping['joinColumns'][0] = array('name' => 'c_id', 'referencedColumnName' => 'id');
             //                $mapping['sourceToTargetKeyColumns']['c_id'] = 'id';
             //                $mapping['joinColumnFieldNames']['c_id'] = 'c_id';
             //                $mapping['targetToSourceKeyColumns']['id'] = 'c_id';
             //                $mapping['id'] = 1;
             //                $mapping['isOwningSide'] = 0;
             //                $mapping['isCascadeRemove'] = 0;
             //                $mapping['isCascadePersist'] = 0;
             //                $mapping['isCascadeRefresh'] = 0;
             //                $mapping['isCascadeMerge'] = 0;
             //                $mapping['isCascadeDetach'] = 0;
             //                $mapping['orphanRemoval'] = 0;
             //                $mapping['type'] = ClassMetadataInfo::MANY_TO_ONE;
             //                $mapping['fetch'] = ClassMetadataInfo::FETCH_LAZY;
             //                $mapping['fieldName'] = 'course';
             //                $mapping['targetEntity'] = 'Entity\\Course';
             //                $mapping['sourceEntity'] = $metadata->name;
             //
             //                $metadata->associationMappings['course'] = $mapping;
             //                $metadata->identifier['course'];
             //                unset($metadata->identifier['c_id']);
             //                unset($metadata->fieldMappings['c_id']);
             //                $mapping = array();
             //                $mapping['cascade'] = array();
             //                $mapping['joinColumns'][0] = array('name' => 'id', 'referencedColumnName' => 'c_id');
             //                $mapping['sourceToTargetKeyColumns']['id'] = 'c_id';
             //                $mapping['joinColumnFieldNames']['id'] = 'id';
             //                $mapping['targetToSourceKeyColumns']['c_id'] = 'id';
             //                $mapping['id'] = 1;
             //                $mapping['isOwningSide'] = 1;
             //                $mapping['isCascadeRemove'] = 0;
             //                $mapping['isCascadePersist'] = 0;
             //                $mapping['isCascadeRefresh'] = 0;
             //                $mapping['isCascadeMerge'] = 0;
             //                $mapping['isCascadeDetach'] = 0;
             //                $mapping['orphanRemoval'] = 0;
             //                $mapping['type'] = ClassMetadataInfo::ONE_TO_MANY;
             //                $mapping['fetch'] = ClassMetadataInfo::FETCH_LAZY;
             //                $name = explode('\\' ,$metadata->name);
             //                $name = end($name);
             //                $name = Inflector::tableize($name);
             //                $mapping['fieldName'] = $name;
             //                $mapping['targetEntity'] = $metadata->name;
             //                $mapping['sourceEntity'] = 'Entity\\Course';
             //                $course->associationMappings[$name] = $mapping;
         }
         $metadata->class_to_extend = $is_course_table ? 'CourseEntity' : 'Entity';
         $repo_factory->writeEntityRepositoryClass($metadata->name, $root . '\\repository\\');
     }
     $generator = new EntityGenerator();
     $generator->setClassToExtend('Entity');
     $generator->setGenerateAnnotations(false);
     $generator->setGenerateStubMethods(true);
     $generator->setRegenerateEntityIfExists(false);
     $generator->setUpdateEntityIfExists(false);
     $generator->setBackupExisting(false);
     $generator->setExtension('.class.php');
     $generator->setNumSpaces(4);
     // Generating Entities
     $generator->generate($metadatas, $root);
     $exporter = new \Doctrine\ORM\Tools\Export\Driver\YamlExporter();
     $exporter->setOutputDir($root . '/mapping');
     foreach ($metadatas as $metadata) {
         echo $metadata->name . '<br/>';
         try {
             $exporter->setMetadata(array($metadata));
             $exporter->export();
         } catch (Exception $e) {
             echo $e->getMessage();
         }
     }
 }