在我的CompilerPass中配置第三方服务

问题描述:

I'm using Symfony 2.7 and I want to configure some service by adding configurator to it. I follow instructions on http://symfony.com/doc/current/components/dependency_injection/configurators.html, but I want to add my configurator to that service in my CompilerPass. I wrote the following code:

$container->getDefinition('exercise_html_purifier.config.default')
    ->setConfigurator([
        $container->getDefinition('application.exercise_html_purifier.config_configurator')->getClass(),
        'configure'
    ]);

where application.exercise_html_purifier.config_configurator is id of my configurator service. This code works as expected, but of course it is also triggers php's warning:

DEPRECATED - Non-static method Application\Service\ExerciseHTMLPurifier\Configurator\ConfigConfigurator::configure() should not be called statically, assuming $this from incompatible context

because the configure method is not static in my case. I can't figure out, how to tell symfony to set non-static configurator callback. I tried to set it like this:

$container->getDefinition('exercise_html_purifier.config.default')
    ->setConfigurator([
        $container->get('application.exercise_html_purifier.config_configurator'),
        'configure'
    ]);

but got this error:

ContextErrorException in XmlDumper.php line 201: Warning: DOMElement::setAttribute() expects parameter 2 to be string, object given

I even tried to use the following syntax:

$container->getDefinition('exercise_html_purifier.config.default')
    ->setConfigurator([
        '@application.exercise_html_purifier.config_configurator',
        'configure'
    ]);

but also got error

FatalErrorException in appDevDebugProjectContainer.php line 2992: Parse Error: syntax error, unexpected '@', expecting identifier (T_STRING)

What I'm doing wrong? Thanks.

OK, I've read the source of \Symfony\Component\DependencyInjection\Dumper\XmlDumper::addService() and found that one of the solutions is to pass Definition instead of instance:

$container->getDefinition('exercise_html_purifier.config.default')
    ->setConfigurator([
        $container->getDefinition('application.exercise_html_purifier.config_configurator'),
        'configure'
    ]);