How to inject a service in another service in Symfony?

Viewed 30280

I am trying to use the logging service in another service in order to trouble shoot that service.

My config.yml looks like this:

services:
    userbundle_service:
        class:        Main\UserBundle\Controller\UserBundleService
        arguments: [@security.context]

    log_handler:
        class: %monolog.handler.stream.class%
        arguments: [ %kernel.logs_dir%/%kernel.environment%.jini.log ]


    logger:
        class: %monolog.logger.class%
        arguments: [ jini ]
        calls: [ [pushHandler, [@log_handler]] ]

This works fine in controllers etc. however I get no out put when I use it in other services.

Any tips?

3 Answers

More versatile option, is to once create a trait for the class you would want to be injected. For instance:

Traits/SomeServiceTrait.php

Trait SomeServiceTrait
{
    protected SomeService $someService;

    /**
     * @param SomeService $someService
     * @required
     */
    public function setSomeService(SomeService $someService): void
    {
        $this->someService = $someService;
    }
}

And where you need some service:

class AnyClassThatNeedsSomeService
{
    use SomeServiceTrait;

    public function getSomethingFromSomeService()
    {
        return $this->someService->something();
    }
}

The class will autoload due to @required annotation. This generaly makes it much faster to implement when you want to inject services into numerous classes (like event handlers).

Related