这里有一个可行的解决方案,但我不建议使用它。我建议你只需使用--package-version
或其他某种选项来执行命令,因为这需要额外的工作量,并且不适用于未来Symfony更新。
第一件事是将bin/
目录中的console
命令复制到一个新命令中,并将use
语句更改为你自己扩展的应用程序:
bin/alt_console:
use AppBundle\Console\Application;
然后创建一个新的Application
类来扩展现有的Symfony应用程序,像这样:
应用程序:
namespace AppBundle\Console;
use AppBundle\Command\YourCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class TestApplication extends Application
{
const NAME = 'Alternative Application';
const VERSION = '1.0';
protected $command;
protected $defaultCommand;
protected $dispatcher;
protected $runningCommand;
public function __construct()
{
parent::__construct(static::NAME, static::VERSION);
$this->add(new YourCommand());
}
public function doRun(InputInterface $input, OutputInterface $output)
{
}
protected function getDefaultInputDefinition()
{
$definition = [];
$defaultDefinition = parent::getDefaultInputDefinition();
foreach ($defaultDefinition->getOptions() as $option) {
if ($option->getName() !== 'version') {
$definition[] = $option;
}
}
foreach ($defaultDefinition->getArguments() as $argument) {
$definition[] = $argument;
}
return new InputDefinition($definition);
}
}
现在,您可以使用自己的
--version
选项将应用程序添加进去:
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class YourCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('your:command')
->addOption('--version', '-V', InputOption::VALUE_NONE, 'okay')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($input->hasOption('version')) {
}
}
}
然后,您可以通过以下方式调用您的命令:
php bin/console your:command
php bin/console your:comand --version
请注意,我不建议这么做。这样做只是为了节省几个按键的时间,但实际上需要付出很多额外的工作量。此外,如果
bin/console
或者
Symfony\Component\Console\Application
在以后发生变化,那么您就必须手动更新这些文件,因为您已经覆盖了它们。
Application::doRun()
有一个硬编码的参数检查,那么对我来说似乎有些不对。CLI应用程序框架不应该强制要求我使用某个命令选项。只需注册一个选项以覆盖任何默认值即可。 - Moritz Friedrich--package-version
。你可以尝试覆盖Application
类并将bin/console
复制到一个新命令中,该命令加载此应用程序,但在那之后你仍然会遇到很多困难。Symfony有一个受保护的getDefaultInputDefinition()
函数,您可以重写并删除version
选项,但doRun()
命令中有一个硬编码检查version
的内容,您必须在删除它的同时复制现有代码。 - Jason Roman