Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 Console command for creating custom Database

I am working on a Symfony 2 project where each user have his own database. In my config.yml file I have a doctrine:dbal:orm set for a client but no connection properties because they are set at runtime and referenced by all users. I.e I only have one default dbal connection and two orm-connection and the amount of users is unlimited.

This works fine but I need to create the database and schema when the user is registered (FOS UserBundle). In the extended userbundle controller I can put my own logic. The problem is that I cannot run the 'php app/console doctrine:database:create' since there are not parameters set for the new user.

Is there any way of specifying a custom database parameter to the console commands? I could probably get around this by some very ugly mysql commands but I'd rather not. Many thanks in advance!

like image 399
user2194860 Avatar asked Mar 21 '13 11:03

user2194860


People also ask

What is Symfony Console Component?

The Console component eases the creation of beautiful and testable command line interfaces. The Console component allows you to create command-line commands. Your console commands can be used for any recurring task, such as cronjobs, imports, or other batch jobs.

What is Symfony CLI?

The Symfony CLI is a developer tool to help you build, run, and manage your Symfony applications directly from your terminal. It's Open-Source, works on macOS, Windows, and Linux, and you only have to install it once in your system. You can use the Symfony CLI to: Create new Symfony applications.

What is schema Symfony?

Symfony's Database Schema. In order to create the data object model that symfony will use, you need to translate whatever relational model your database has to an object data model. The ORM needs a description of the relational model to do the mapping, and this is called a schema.

What is entity Symfony?

Well, entity is a type of object that is used to hold data. Each instance of entity holds exactly one row of targeted database table. As for the directories, Symfony2 has some expectations where to find classes - that goes for entities as well.


1 Answers

You can create your own command using the code below as an outline:

namespace Doctrine\Bundle\DoctrineBundle\Command;

use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\DBAL\DriverManager;

class CreateDatabaseDoctrineCommandDynamically extends DoctrineCommand
{

    protected function configure()
    {
        $this
            ->setName('doctrine:database:createdynamic')
            ->setDescription('Creates the configured databases');
    }

    /**
     * {@inheritDoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
    /***
        **   Edit this part below to get the database configuration however you want
        **/
        $connectionFactory = $this->container->get('doctrine.dbal.connection_factory');
        $connection = $connectionFactory->createConnection(array(
        'driver' => 'pdo_mysql',
         'user' => 'root',
         'password' => '',
         'host' => 'localhost',
         'dbname' => 'foo_database',
        ));

        $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);
            $output->writeln(sprintf('<info>Created database for connection named <comment>%s</comment></info>', $name));
        } catch (\Exception $e) {
            $output->writeln(sprintf('<error>Could not create database for connection named <comment>%s</comment></error>', $name));
            $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
            $error = true;
        }

        $tmpConnection->close();

        return $error ? 1 : 0;
    }
}
like image 200
james_t Avatar answered Oct 09 '22 16:10

james_t