How do I inject a class instead of a service in Symfony?

I would like to get the following (without using services.yml - ideally, through some annotation mechanism if the hint type cannot do that):

class MyClass {
    private $msgService;

    public function __construct(MessageServiceInterface $msgService) {
        $this->msgService = $msgService;
    }

    public function sendMessage($text) {
        $this->msgService->send($text);
    }
}

      

Basically, I would like Symfony to be able to tell MyClass to be aware of dependency injection and to have a MessageServiceInterface injected.

I find it quite time consuming to define a service for every class that I need to use (especially if those classes are to be used only within that module and possibly only once).

+3


source to share


1 answer


You can simplify the definition and use of the service with JMSDiExtraBundle . This bundle provides advanced dependency injection functionality for Symfony2. Especially in Annotation, you can do something like:

Marks the class as a service:

<?php

use JMS\DiExtraBundle\Annotation\Service;

/**
 * @Service("some.service.id", parent="another.service.id", public=false)
 */
class Listener
{
}

      

Specifies method parameters for injection:



<?php

use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Service;

/**
 * @Service
 */
class Listener
{
    /**
     * @InjectParams({
     *     "em" = @Inject("doctrine.entity_manager")
     * })
     */
    public function __construct(EntityManager $em, Session $session)
    {
        // ...
    }
}

      

All without any additional config files.

Hope for this help

+1


source







All Articles