如何在symfony中收听控制台事件?

acm*_*cme 5 symfony

我正在尝试使用symfony标准版(2.3)挂钩symfonys控制台事件,但它无法正常工作.

我根据他们的例子创建了一个监听器,并按照事件注册指南进行操作:

namespace Acme\DemoBundle\EventListener;

use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\ConsoleEvents;

class AcmeCommandListener
{
    public function onConsoleCommand(ConsoleCommandEvent $event) {
        // get the output instance
        $output = $event->getOutput();

        // get the command to be executed
        $command = $event->getCommand();

        // write something about the command
        $output->writeln(sprintf('Before running command <info>%s</info>', $command->getName()));
    }
}
Run Code Online (Sandbox Code Playgroud)

邮件列表中的某个人告诉我将其注册为服务容器中的事件.所以我这样做了:

services:
    kernel.listener.command_dispatch:
        class: Acme\DemoBundle\EventListener\AcmeCommandListener
        tags:
            - { name: kernel.event_listener, event: console.command }
Run Code Online (Sandbox Code Playgroud)

但显然标记不正确,我找不到正确的名称.我该怎么办?

acm*_*cme 1

所以,我终于明白了。原始帖子中的上述代码完全有效,但我在捆绑包中而不是在应用程序配置中定义了 services.yml app/config.yml。这意味着,配置从未加载。我必须通过容器扩展导入配置:

# Acme/DemoBundle/DependencyInjection/AcmeDemoExtension.php
namespace Acme\DemoBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

class AcmeDemoExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}
Run Code Online (Sandbox Code Playgroud)

# Acme/DemoBundle/DependencyInjection/Configuration.php
namespace Acme\DemoBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('headwork_legacy');
        return $treeBuilder;
    }
}
Run Code Online (Sandbox Code Playgroud)

不过我想你甚至可以省略这个$configuration = new Configuration();部分和Configuration班级。