【问题标题】:Symfony 2 Console command for creating custom DatabaseSymfony 2 控制台命令用于创建自定义数据库
【发布时间】:2013-03-10 21:30:33
【问题描述】:
我正在开发一个 Symfony 2 项目,其中每个用户都有自己的数据库。在我的 config.yml 文件中,我为客户端设置了一个学说:dbal:orm,但没有连接属性,因为它们是在运行时设置并被所有用户引用。即我只有一个默认的 dbal 连接和两个 orm 连接,并且用户数量是无限的。
这工作正常,但我需要在用户注册时创建数据库和架构(FOS UserBundle)。在扩展的 userbundle 控制器中,我可以放置自己的逻辑。
问题是我无法运行 'php app/console dictionary:database:create',因为没有为新用户设置参数。
有没有办法为控制台命令指定自定义数据库参数?
我可能可以通过一些非常丑陋的 mysql 命令来解决这个问题,但我宁愿不这样做。
非常感谢!
【问题讨论】:
标签:
mysql
symfony
console
doctrine
dbal
【解决方案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;
}
}