我如何使用" src / config / config.yml"与Doctrinbe DBAL。 现在我正在使用一个返回配置数组DBAL需要使用的静态函数。
静态配置文件 SRC /配置/ AppConfig.php
protected static $dbserver = array(
'dbname' => 'db-name',
'user' => 'user',
'password' => 'password',
'host' => 'localhost',
'driver' => 'pdo_mysql',
'charset' => 'utf8',
);
在构造函数中它看起来像这个
public function __construct()
{
$this->connect();
}
private function connect()
{
$this->config = new \Doctrine\DBAL\Configuration();
$this->conn = \Doctrine\DBAL\DriverManager::getConnection(AppConfig::getDbserver(), $this->config);
}
这是控制台命令的类
namespace Mts\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Mts\Utilities\SanitizeScan;
class SanitizeScanCommand extends ContainerAwareCommand
{
protected function configure()
{
$this->setName('sanitize:scan');
$this->setDescription('Scan DB and Filesystem for invalid Filenames and write Result(s) to Log.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$helper = $this->getHelper('question');
$question = new ChoiceQuestion(
'Please Select what to Scan (defaults to both)',
array('both', 'Database', 'Filesystem'),
0
);
$question->setErrorMessage('%s is invalid.');
$logtype = $helper->ask($input, $output, $question);
# get config.yml from src/config/
$conn = $this->getContainer()->get('doctrine')->getConnection();
print_r($conn);
$log = new SanitizeScan($logtype);
$log->create();
}
}
目标是使用它:
doctrine:
dbal:
dbname:
host: localhost
port: 3306
user:
password:
driver: pdo_mysql
charset: UTF8
logging: '%kernel.debug%'
答案 0 :(得分:1)
在控制器中,您可以使用
获得学说$doctrine = $this->getDoctrine();
在自定义类中,您可以注入服务容器而不是
$doctrine = $this->container->get('doctrine');
而不是从学说中获得连接
/**
* @var \Doctrine\DBAL\Driver\Connection $conn
*/
$conn = $doctrine->getConnection();
更新 - 最小工作示例
在命令中,您可以使用ContainerAwareCommand
<?php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class TestCommand extends ContainerAwareCommand
{
protected function configure()
{
$this->setName('app:test');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$conn = $this->getContainer()->get('doctrine')->getConnection();
dump($conn);
}
}