2013-03-21 3 views
6

私は自分のデータベースを持っているSymfony 2プロジェクトに取り組んでいます。私のconfig.ymlファイルでは、私はdoctrine:dbal:ormがクライアント用に設定されていますが、実行時に設定され、すべてのユーザーが参照するため、接続プロパティは設定されていません。私は1つのデフォルトのdbal接続と2つのorm接続しか持たず、ユーザー数は無制限です。Symfony 2カスタムデータベースを作成するためのコンソールコマンド

これは問題なく動作しますが、ユーザーが登録されるとデータベースとスキーマを作成する必要があります(FOS UserBundle)。拡張されたユーザバンドルコントローラでは、自分のロジックを置くことができます。 問題は、新しいユーザーにパラメータが設定されていないため、 'php app/console doctrine:database:create'を実行できないということです。

カスタムデータベースパラメータをコンソールコマンドに指定する方法はありますか。 私はおそらくこれをいくつかの非常に醜いmysqlコマンドで回避することができますが、私はむしろそうしたくありません。 事前に感謝します!

+1

あなたが唯一の接続ではなく、パラメータを渡すことができます。あなた自身のコマンドを作成してください! – Venu

答えて

1

アウトラインとして以下のコードを使用して、独自のコマンドを作成することができます。

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; 
    } 
} 
関連する問題