Symfony 2控制台命令创建自定义数据库
问题描述:
我正在Symfony 2项目,其中每个用户有他自己的数据库。在我的config.yml文件中,我有一个教条:dbal:orm为客户端设置,但没有连接属性,因为它们是在运行时设置的并且由所有用户引用。即,我只有一个默认的dbal连接和两个orm-connection,用户数量是无限的。Symfony 2控制台命令创建自定义数据库
这工作正常,但我需要在用户注册(FOS UserBundle)时创建数据库和架构。在扩展的用户捆绑控制器中,我可以放置自己的逻辑。 问题是我无法运行'php app/console doctrine:database:create',因为没有为新用户设置参数。
是否有任何方式为控制台命令指定自定义数据库参数? 我可以通过一些非常丑陋的mysql命令解决这个问题,但我宁愿不要。 非常感谢提前!
答
您可以使用下面的代码作为轮廓创建自己的命令:
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;
}
}
只能通过连接,但没有参数。更好地创建自己的命令! – Venu 2013-03-22 10:15:56