2013-03-21 98 views
6

我正在Symfony 2項目,其中每個用戶有他自己的數據庫。在我的config.yml文件中,我有一個教條:dbal:orm爲客戶端設置,但沒有連接屬性,因爲它們是在運行時設置的並且由所有用戶引用。即,我只有一個默認的dbal連接和兩個orm-connection,用戶數量是無限的。Symfony 2控制檯命令創建自定義數據庫

這工作正常,但我需要在用戶註冊(FOS UserBundle)時創建數據庫和架構。在擴展的用戶捆綁控制器中,我可以放置自己的邏輯。 問題是我無法運行'php app/console doctrine:database:create',因爲沒有爲新用戶設置參數。

是否有任何方式爲控制檯命令指定自定義數據庫參數? 我可以通過一些非常醜陋的mysql命令解決這個問題,但我寧願不要。 非常感謝提前!

+1

只能通過連接,但沒有參數。更好地創建自己的命令! – Venu 2013-03-22 10:15:56

回答

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; 
    } 
}