8

我正在尝试使用 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()));
    }
}

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

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

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

4

3 回答 3

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

?>
于 2021-01-08T20:41:40.253 回答
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');
    }
}

# 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类。

于 2013-09-05T13:00:24.157 回答
1

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

services:
    kernel.listener.command_dispatch:
        class: Acme\DemoBundle\EventListener\AcmeCommandListener
        tags:
            - { name: console.event_listener, event: console.command }
于 2020-05-27T06:32:41.830 回答