Как использовать config.yml с DBAL

Как я могу использовать "src/config/config.yml" с Doctrinbe DBAL. Прямо сейчас я использую статическую функцию, которая возвращает массив конфигурации, с которым DBAL должен работать.

статический конфигурационный файл src/config/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%'

1 ответ

В контроллере вы можете получить учение с

$doctrine = $this->getDoctrine();

В пользовательском классе вы можете добавить контейнер службы и затем

$doctrine = $this->container->get('doctrine');

и чем из доктрины вы можете получить связь

/**
 * @var \Doctrine\DBAL\Driver\Connection $conn
 */
$conn = $doctrine->getConnection();

см. также Как использовать Doctrine DBAL

Обновление - минимальный рабочий пример

в команде вы можете использовать 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);
    }
}

см. Консоль - Получение сервисов из сервисного контейнера

Другие вопросы по тегам