Tjaari76
Tjaari76

Reputation: 46

How to create database in doctrine2 (standalone)

I'm using Doctrine2 in a PHP project (out of Symfony).

How can I create a database from code ?

Like done by the php app/console doctrine:database:create command in a Symfony project.

I have the same kind of database than a simple symfony project on pdo_mysql driver.

I found everything about the database connection, schema creation, mapping, entity manager, ... in the documentation, but nothing about create the database really.

I'm pretty sure to know how to it with an hard-coded MySQL query (i.e. CREATE DATABASE ...),
I'm looking for use of doctrine tools (if exists, of course).

Upvotes: 1

Views: 600

Answers (1)

chalasr
chalasr

Reputation: 13167

You seems to be right, I can't find doc about this.

A short variant of what is done by the doctrine:database:create command:

<?php

public function createDatabase($name, array $config)
{
    /** @var \Doctrine\DBAL\Connection */
    $tmpConnection = \Doctrine\DBAL\DriverManager::getConnection($config);

    // Check if the database already exists
    if (in_array($name, $tmpConnection->getSchemaManager()->listDatabases())) {
        return;
    }

    // Create the database
    $tmpConnection->getSchemaManager()->createDatabase($name);
    $tmpConnection->close();
}

Example usage:

$this->createDatabase('symfony', array(
    'driver'   => 'pdo_mysql',
    'host'     => '127.0.0.1',
    'user'     => 'db_user',
    'password' => 'db_password',
));

The doctrine SchemaManager documentation (which doesn't talk about the expected method).

Upvotes: 2

Related Questions