Dynamic databases and schema creation in Symfony/Doctrine
Asked Answered
P

1

5

I want to store database connections in a static database. On demand I want to create a new database, store the credentials in my static database and then create the schema inside the new database from existing entities. I know how to do that by using symfony's command line tool. My goal is to make it work in a service. I looked into the Doctrine docs and try to make something work:

    $conn =$this->getDoctrine()->getConnection()->getSchemaManager()->createDatabase($dbname);
    $isDevMode = true;
    $config = Setup::createAnnotationMetadataConfiguration(array('UiCoreDbBundle/Entity'), $isDevMode);

    $conn = array(
        'driver' => 'pdo_mysql',
        'host' => '127.0.0.1',
        'user' => 'root',
        'dbname' => $dbname
    );
    $em = EntityManager::create($conn,$config);

    $tool = new SchemaTool($em);
    $classes = array(
      $em->getClassMetadata('Product')
      //...
    );

    $tool->createSchema($classes);

My example code does not work like i hoped it would. Doctrine can't find my entities. Can anyone give me a hint on the proper way to implement such a task?

Prostatectomy answered 30/3, 2016 at 11:3 Comment(0)
P
8

I came up with a solution and want to leave the code snippet for future generations:

/**
 * @param  string $dbname
 * @throws \Doctrine\ORM\ORMException
 * @throws \Doctrine\ORM\Tools\ToolsException
 */
public function createDatabase($dbname)
{
    $this->em->getConnection()->getSchemaManager()->createDatabase($dbname);
    $params = $this->em->getConnection()->getParams();
    $conn = array(
        'driver' => $params['driver'],
        'host' => $params['host'],
        'user' => $params['user'],
        'dbname' => $dbname
    );
    $newEm = EntityManager::create($conn,$this->em->getConfiguration(), $this->em->getEventManager());
    $meta = $this->em->getMetadataFactory()->getAllMetadata();

    $tool = new SchemaTool($newEm);
    $tool->createSchema($meta);
}

Basically I am coping my existing default entity manager, which knows my entities and make some parameter changes. Instead of getAllMetadata you can add the classes manually using:

$meta = array(
      $newEm->getClassMetadata('Bundlename:Entityclass')   
      //...
    );

Please let me know, if someone knows a better way. Cheers

Prostatectomy answered 1/4, 2016 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.