Symfony 2 Console Team to Create a Custom Database

I am working on a Symfony 2 project where each user has their own database. In my config.yml file, I have the doctrine: dbal: orm is set for the client, but there are no connection properties because they are set at runtime and are referenced by all users. Ie I have only one standard dbal connection and two orm connections, and the number of users is unlimited.

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

Is there a way to specify a custom database setting for console commands? I could get around this with some very ugly mysql commands, but I would prefer. Thank you very much in advance!

+6
source share
1 answer

You can create your own team using the following code:

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; } } 
+1
source

All Articles