Doctrine 2.3 Entity Generator: samples, docs?

2019-05-31 15:45发布

Doctrine can generate entities based on small data input, including relation information. However, i have failed to find any example or concise information on the topic. The official documentation only has a small paragraph, with a minor command line example, explaining absolutely nothing,

Can anyone refer to a book, article or even code sample of this?

2条回答
成全新的幸福
2楼-- · 2019-05-31 15:58

I usually declare the metadata in yml, and initially generate classes and database from there.

Here is a complete example along with the yml metadata files:

//example.php

   function getDbConfig()
   {
      //An example configuration
      return array(
         'driver'   => 'pdo_mysql',
         'user'     => 'root',
         'password' => 'potatoes',
         'dbname'   => 'garden',
         'host'     => 'localhost',
         'charset' => 'utf8',
               'driverOptions' => array(
                  1002=>'SET NAMES utf8'
               )
      );
   }

   function bootstrapDoctrine()
   {
      require_once ($this->_libDir . DS . 'Doctrine/ORM/Tools/Setup.php');
      Doctrine\ORM\Tools\Setup::registerAutoloadDirectory('/full/path/to/lib');//So that Doctrine is in /full/path/to/lib/Doctrine   
   }

   function getEntityFolders()
   {
      //An example configuration of two entity folders
      return array(
         '/full/path/to/App/Module1/Entities/yml' => '\\App\\Module1\\Entities',
         '/full/path/to/App/Module2/Entities/yml' => '\\App\\Module2\\Entities'
      );
   }

   function setupDoctrine()
   {
      $config = Doctrine\ORM\Tools\Setup::createConfiguration();
      $driver = new \Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver(getEntityFolders());
      $driver->setGlobalBasename('schema');
      $config->setMetadataDriverImpl($driver);

      $entityManager = \Doctrine\ORM\EntityManager::create($dbConfig, $config);
      return $entityManager;
   }

   function getEntitiesMetaData($em)
   {
      $cmf = new Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
      $cmf->setEntityManager($em);  // we must set the EntityManager

      $driver = $em->getConfiguration()->getMetadataDriverImpl();

      $classes = $driver->getAllClassNames();
      $metadata = array();
      foreach ($classes as $class) {
        //any unsupported table/schema could be handled here to exclude some classes
        if (true) {
          $metadata[] = $cmf->getMetadataFor($class);
        }
      }
      return $metadata;
   }

   function generateEntities($rootDir, $metadata)
   {
      $generator = new Doctrine\ORM\Tools\EntityGenerator();
      $generator->setUpdateEntityIfExists(true);    // only update if class already exists
      //$generator->setRegenerateEntityIfExists(true);  // this will overwrite the existing classes
      $generator->setGenerateStubMethods(true);
      $generator->setGenerateAnnotations(true);
      $generator->generate($metadata, $rootDir);
   }

   function generateDatabase()
   {
      $schema = new Doctrine\ORM\Tools\SchemaTool($em);
      $schema->createSchema($metadata);
   }

   //Sets up the Doctrine classes autoloader
   bootstrapDoctrine();
   //Sets up database connection, schema files (yml) and returns the EntityManager
   $em = setupDoctrine();
   //Returns the metadata specified by the two schema.orm.yml files
   $metadata = getEntitiesMetaData($em);
   /* Generates the classes based on the yml schema. Using the yml files in the example
    * the result will be the following files:
    *    /full/path/to/App/Module1/Entities/User.php
    *    /full/path/to/App/Module2/Entities/Comment.php
    *    /full/path/to/App/Module2/Entities/Page.php
    */
   generateEntities('/full/path/to', $metadata);
   //Now generate database tables:
   generateDatabase($metadata);

And the example schema files: YAML schema for module1:

  # /full/path/to/App/Module1/Entities/yml/schema.orm.yml
  App\Module1\Entities\User:
    type: entity
    table: user
    id:
      id:
        type: integer
        generator:
          strategy: AUTO
    fields:
      name:
      email:

YAML Schema for module 2:

  # /full/path/to/App/Module2/Entities/yml/schema.orm.yml
  App\Module2\Entities\Page:
    type: entity
    table: page
    id:
      id:
        type: integer
        generator:
          strategy: AUTO
    fields:
      name:
      content:
        type: text

  App\Module2\Entities\Comment:
    type: entity
    table: comment
    id:
      id:
        type: integer
        generator:
          strategy: AUTO
    fields:
      comment_date:
        type: datetime
      content:
        type: text
    manyToOne:
      user:
        targetEntity: App\Module1\Entities\User

Please note that I was using the SimplifiedYamlDriver Metadata driver that can load multiple entities from a single yml file.

This is a working example, I use these exact steps for generating class files and db from yml. Additionally, the Getting Started tutorial contains quite several yml examples.

查看更多
成全新的幸福
3楼-- · 2019-05-31 16:11

First you need to bootstrap Doctrine and get an instance of EntityManager, then you once you have it, you can do the following:

    $cmf = new Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
    $cmf->setEntityManager($em); // $em is EntityManager instance
    $metadata = $cmf->getAllMetadata();
    $generator = new \Doctrine\ORM\Tools\EntityGenerator();
    $generator->setGenerateAnnotations(true);
    $generator->setGenerateStubMethods(true);
    $generator->setRegenerateEntityIfExists(true);
    $generator->setUpdateEntityIfExists(false);
    $generator->generate($metadata, '/path/to/entities');

For more information on the configuration, read this:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/configuration.html

查看更多
登录 后发表回答