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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.