I am using a modified copy of yadif as my dependency injection framework.
Currently, I have created an abstract class called AContainerAware which is similiar to symfony2's ContainerAware:
abstract class AContainerAware{
protected $_container;
public function setContainer(Container $container){
$this->_container = $container;
}
protected function get($component){
//return a component from $this->_container;
}
}
This works well in most cases. I just have class who require the container to extend AContainerAware, and the container is automatically injected by the DI framework during object creation using setContainer()
. I can then easily get components from the container.
The issue is when working with third party vendor packages. In those cases, for example writing an extension for twig requires me to extend the Twig_Extension
class, which means I can't extend AContainerAware
to get access to the container.
I am considering whether to turn AContainerAware
into an interface IContainerAware
. Since classes can implement multiple interfaces, IContainerAware
should be implementable in most cases. The only issue with this approach is that one cannot write any code for setContainer()
and get()
in an interface, so it is repetitive to have to implement the exact code for those functions in each class that requires the container. It also poses maintainance issues if setContainer()
and get()
were to change in the future.
Is there a better way to mark a class for container injection?