Ignore missing methods in setter injection

Ignore missing methods in setter injection

I’m using PHP traits as mixins to inject optional services, i.e.

<?php

trait Logger
{
    private LoggerInterface $logger;

    public function getLogger(): LoggerInterface
    {
        return $this->logger;
    }

    /**
     * Inject logger instance (called by the DI container)
     */
    public function setLogger(LoggerInterface $logger): self
    {
        $this->logger = $logger;

        return $this;
    }
}

Then I use this trait in a class:

class UserService
{
    use Logger;
    /* ... */
}

Because this trait can be used in any class, I create a method injection call for all classes in App namespace to inject the logger:

App:
    # ...
    calls:
        - [setLogger, ['@monolog.logger']]

However, when Symfony encounters a service that doesn’t implement setLogger method, it throws an error saying ‘Invalid service: method “setLogger()” does not exist.’

Since this injection is supposed to be optional, is there a way to tell Symfony to ignore the call if the method does not exist?

Source: Symfony Questions

Leave a Reply

Your email address will not be published. Required fields are marked *