Symfony2 - 控制台命令,如何设置环境配置?

时间:2013-12-27 12:19:52

标签: php symfony

我正在尝试使用Symfony2控制台组件(没有整个Symfony2框架),并且不确定根据我的环境加载特定配置文件的最佳实践方法。

在我的用例中,我纯粹使用Console组件(如果需要,我可以使用其他组件)但不确定如何根据我的环境加载特定的配置文件。

<?php
// app/console
// Include composer autloader
$loader = require_once dirname(dirname(__FILE__)) . '/vendor/autoload.php';
require_once dirname(__FILE__) . '/AppKernel.php';

use Symfony\Component\Console\Input\ArgvInput;

// Determine which environment we are on
$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);

// The following line won't work because composer loader doesn't implement "Symfony\Component\Config\Loader\LoaderInterface"
$kernel->registerContainerConfiguration($loader);

$console = new Cli\Console($kernel);
$console->setCatchExceptions(TRUE);
$console->run();

<?php
// app/AppKernel.php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array();
        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

<?php

namespace Tel\Cli;

use Symfony\Component\Console\Application;
use Cli\Command;

/**
 * Console application
 */
class Console extends Application {

    /**
     * Console constructor.
     */
    public function __construct($kernel) {
        parent::__construct('Application name', '1.0');

        $this->kernel = $kernel;

        // @TODO - Get these commands from DB/config file
        $this->addCommands(array(
            new Command\P1,
            new Command\P2,
            new Command\P3,
        ));
    }
}

1 个答案:

答案 0 :(得分:2)

默认情况下会加载app / config.yml,此外还会根据您的环境加载另一个配置文件。 您可以指定命令的环境:

php app/console myCommand --env=prod

为了访问参数,您的命令可以扩展抽象类Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand,在这种情况下,您将访问:

  • 服务:$this->getContainer()->get('service_id')
  • 参数:$this->getContainer()->getParameter('parameter_name')