1

我想在用户注册时为他创建数据库。创建数据库的代码如下所示

$connectionFactory = $this->container->get('doctrine.dbal.connection_factory');
$connection = $connectionFactory->createConnection(array(
    'driver' => 'pdo_mysql',
    'user' => 'root',
    'password' => 'mysecretpassword',
    'host' => 'localhost',
    'dbname' => 'userdatabase',
));

$params = $connection->getParams();
$name = isset($params['path']) ? $params['path'] : $params['dbname'];

unset($params['dbname']);

$tmpConnection = DriverManager::getConnection($params);

// Only quote if we don't have a path
if (!isset($params['path'])) {
    $name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name);
}

$error = false;
try {
    $tmpConnection->getSchemaManager()->createDatabase($name);
    echo sprintf('<info>Created database for connection named <comment>%s</comment></info>', $name);
} catch (\Exception $e) {
    echo sprintf('<error>Could not create database for connection named <comment>%s</comment></error>', $name);
    echo sprintf('<error>%s</error>', $e->getMessage());
    $error = true;
}

$tmpConnection->close();

我在 AccountBundle 中为该数据库创建了实体,但不知道在创建用户数据库时如何创建数据库模式。

4

1 回答 1

1

它经常在测试中使用。在LiipFunctionalTestBundle中可以看到一个示例。

$metadatas = $om->getMetadataFactory()->getAllMetadata();
$schemaTool = new SchemaTool($om);
$schemaTool->dropDatabase($name);
if (!empty($metadatas)) {
    $schemaTool->createSchema($metadatas);
}
于 2013-04-27T16:22:18.390 回答