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

时间:2013-09-04 15:01:38

标签: symfony

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

我根据example创建了一个监听器,并按照guides on event registration

进行操作
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()));
    }
}

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

services:
    kernel.listener.command_dispatch:
        class: Acme\DemoBundle\EventListener\AcmeCommandListener
        tags:
            - { name: kernel.event_listener, event: console.command }

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

3 个答案:

答案 0 :(得分:2)

Platform\EventListener\Console\InitListener:
    tags:
        - { name: kernel.event_listener, event: console.command, priority: 1024 }

<?php 
class CustomListener
{
    public function onConsoleCommand(ConsoleCommandEvent $event): void
    {
        //do somehting
    }
}

?>

答案 1 :(得分:1)

所以,我终于明白了。原始帖子中的上述代码完全正常工作,但我在我的bundle中定义了我的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');
    }
}

# 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;
    }
}

虽然我猜您甚至可以省略$configuration = new Configuration();部分和Configuration课程。

答案 2 :(得分:1)

您的tags事件侦听器名称必须为console.event_listener。它帮助我解决了这个问题。

services:
    kernel.listener.command_dispatch:
        class: Acme\DemoBundle\EventListener\AcmeCommandListener
        tags:
            - { name: console.event_listener, event: console.command }