This question is not strictly related to Symfony 2, but since I use Symfony 2 components and most likely will use Symfony \ Component \ DependencyInjection \ Container as a DI container, this may be relevant.
I am currently creating a small library using components from Symfony 2, for example. HttpFoundation, Validator, Yaml. My domain services extend the basic function of AbstractService, providing nothing but Doctrine \ ORM \ EntityManager and Symfony \ Component \ Validator \ Validator through constructor injection as follows:
abstract class AbstractService { protected $em; protected $validator; public function __construct(EntityManager $em, Validator $validator) { $this->em = $em; $this->validator = $validator; } }
The Service class extending this AbstractService may now be required to add additional components, such as Symfony \ Component \ HttpFoundation \ Session. I do it like this:
class MyService extends AbstractService { protected $session; public function __construct(Session $session, EntityManager $em, Validator $validator) { parent::__construct($em, $validator); $this->session = $session; } }
Is there a more elegant way to solve this problem without repeating the arguments of the parent constructor, for example. using Setter-Injection for Session instead?
As I see it, when I use Setter-Injection for Session, I have to add checks before accessing them in my methods, regardless of whether it has already been entered and what I want to avoid. On the other hand, I do not want to βrepeatβ the injection of the main components shared by all services.
source share