0

I am trying to override a service by using a ServiceProvider Class

class MyModuleServiceProvider extends ServiceProviderBase
{
    public function alter(ContainerBuilder $container)
    {
        // Overrides MessageNotifier class to add loggin facilities to each message.
        $definition = $container->getDefinition('message_notify.sender');
        $definition->setClass('Drupal\my_module\MyModuleMessageNotifier')->addArgument([
            new Reference('logger.channel.message_notify')
        ]);
    }
}

This is out of topic, but FYI, the overrode service "message_notify.sender" is created by the message_notify module pertaining to the message stack modules

As you can see, I am adding an argument (a logger) to my new service

Here is the __construct() method of the parent (overrode) class:

  public function __construct(Manager $notifier_manager) {
    $this->notifierManager = $notifier_manager;
  }

Here is the __construct() method of my new class:

    public function __construct(Manager $notifier_manager, LoggerChannelInterface $logger)
    {
        parent::__construct($notifier_manager);
        $this->logger = $logger;
    }

But for an unknown reason the $logger variable is not an object but an array with one item... and this item is the LoggerChannel object.

Thus this code is not working but the following does:

    public function __construct(Manager $notifier_manager, array $logger)
    {
        parent::__construct($notifier_manager);
        $this->logger = $logger[0];
    }

What am I doing wrong?

2

The problem is that you are adding your argument as an array, so your __construct() method receives an array. So this:

$definition->setClass('Drupal\my_module\MyModuleMessageNotifier')->addArgument([
  new Reference('logger.channel.message_notify')
]);

Should be this:

$definition->setClass('Drupal\my_module\MyModuleMessageNotifier')
  ->addArgument(new Reference('logger.channel.message_notify'));

(notice that the Reference is not wrapped in an array.

| improve this answer | |
  • I feel realy stupid... many thanks Jaypan for your help!!! – Baud Apr 6 at 23:13
  • Nothing to feel stupid about. We've all been there - sometimes you just need another set of eyes. – Jaypan Apr 7 at 1:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.