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?

0

1 Answer 1

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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