0

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?

F21
  • 32,163
  • 26
  • 99
  • 170
  • You can extend multiple classes like this: http://stackoverflow.com/questions/356128/can-i-extend-a-class-using-more-than-1-class-in-php – Rijk Jan 04 '12 at 08:19
  • I don't really like faking multiple inheritance with `__call()` though, doesn't seem very elegant to me. It also requires a copy of one of the classes to be instantiated within the class, which kind of defeats dependency injection. – F21 Jan 04 '12 at 08:34

1 Answers1

-1

You can use PHP traits which were introduced in PHP 5.4.

Traits enable horizontal reuse of code, whereas inheritance is vertical reuse. A class can use multiple traits, whereas you can only inherit one parent class.

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261