Reputation: 2596
I'd like to achieve the following (without using services.yml - ideally, through some annotation mechanism if the type hinting can't do it):
class MyClass {
private $msgService;
public function __construct(MessageServiceInterface $msgService) {
$this->msgService = $msgService;
}
public function sendMessage($text) {
$this->msgService->send($text);
}
}
Basically, I'd like Symfony to be able to tell that MyClass needs to be aware of dependency injection and needs to have an implementation of MessageServiceInterface injected.
I find it quite time consuming to define a service for each class that I need to use (especially if those classes are to be used only within that module, and maybe only even once).
Upvotes: 4
Views: 704
Reputation: 39430
You can simplify the service definition and usage with the JMSDiExtraBundle. This bundle provide Advanced Dependency Injection Features for Symfony2. Especially the Annotation features you can do something like:
Marks a class as service:
<?php
use JMS\DiExtraBundle\Annotation\Service;
/**
* @Service("some.service.id", parent="another.service.id", public=false)
*/
class Listener
{
}
This marks the parameters of a method 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 extra configuration files.
Hope this help
Upvotes: 1