Neuigkeiten, pattern

Dependency Injection in TYPO3 4.x

What is dependency injection

Its a concept following the IoC (=Inversion of Control) principle. 

In object oriented programming most of the objects needs other objects in order to solve the task. Normally this might be done simply this way:

$object= new class_i_need();

That means your class depends on another class. And it gets the dependency itself. If you want to Unit Test this class you (more or less) cannot really test this class alone because you will also depend on the dependency.

Dependency injection means that the object itself is not responsible of getting the instances it needs - instead it is "injected" from outside.

The most common way is constructor injection - the first step therefore is to explicit request the dependency in the constructor of your class:

class foo {  
public function __construct(class_i_need $object) {
$this->object=$object;
}
}

So now the class cleary describe the dependency - and whoever wants to instanciate this class needs to pass the correct object instance. This way you allready can build better Unit Tests for this class - using Mock or Stub objects.

The next step is that a framework is responsible for resolving the dependency, so creating a instance of your class would look something like:

$myFooInstance=tx_picocontainer_IoC_manager:create('foo');

The framework knows all the available classes and is responsible for resolving the dependency. So it will inject a "class_i_need" instance to the "foo" class and return a correct instance.

The extension "picocontainer"

typo3.org/extensions/repository/view/picocontainer/current/

It includes the PHP implementation of picocontainer: www.picocontainer.org

The extension offers basic dependency injection. The usage itself is simple:

  1. you need to register your classes to the "IoC manager"
  2. then you can ask the manager for instances, and it will resolve the dependencies (if it can).

For usage you need to distinguish between singleton classes (only one instance of a class required) and prototype classes:

 

//registering a singleton class
tx_picocontainer_IoC_manager::registerSingleton(CLASSNAME)
//getting a singleton instance
$object=tx_picocontainer_IoC_manager::getSingleton(CLASSNAME);
//registering a prototype class:
tx_picocontainer_IoC_manager::registerPrototype(CLASSNAME);
//get a new instance:
$object=tx_picocontainer_IoC_manager::create(CLASSNAME)

The registration can be done directly in the head of your class code, or on a central place in your extension.

 

 

blog comments powered by Disqus
blogroll