Enabling Doctrine DBAL commands in Symfony app/console

故事扮演 提交于 2019-12-03 16:35:47

I found a workaround for this, as you may call it that, or maybe rather just a way to enable the commands.

By adding a Command to one of your own bundles (or a dedicated one, is up to you), you can simply subclass the Doctrine command. E.g. to enable the dbal:import command use the following:

namespace Acme\Bundle\AcmeBundle\Command\Doctrine;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;

class ImportCommand extends \Doctrine\DBAL\Tools\Console\Command\ImportCommand {

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getApplication()->getKernel()->getContainer();

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

        $em = $doctrine->getEntityManager();
        $db = $em->getConnection();

        $helperSet = $this->getHelperSet();
        $helperSet->set( new ConnectionHelper( $db ), 'db' );
        $helperSet->set( new EntityManagerHelper( $em ), 'em' );

        parent::execute( $input, $output );
    }

}

As you can see, we simply subclass the original command. Since the database configuration is managed by Symfony we need to get the entity manager through the container. Once we update the HelperSet we pass execution back to the parent class.

Philip Frank

Put this as cli-config.php into your project's root directory. This will enable the --env parameter for php vendor/bin/doctrine. It is "inspired" by Symfony's app/console file.

Note this is for Doctrine <=2.3, see the docs for newer versions.

<?php
require_once __DIR__.'/app/bootstrap.php.cache';
require_once __DIR__.'/app/AppKernel.php';

use Symfony\Component\Console\Input\ArgvInput;

$input = new ArgvInput();
$env = $input->getParameterOption(array('--env', '-e'), getenv('SYMFONY_ENV') ?: 'dev');
$debug = getenv('SYMFONY_DEBUG') !== '0' && !$input->hasParameterOption(array('--no-debug', '')) && $env !== 'prod';

$kernel = new AppKernel($env, $debug);
$kernel->boot();

$em = $kernel->getContainer()->get('doctrine.orm.entity_manager');

$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
    'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
    'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
));

return $helperSet;

Doctrine commands are available in symfony projects through the DoctrineBundle (since version 1.6.4).

You can now run php bin/console doctrine:database:import [files].

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!