Skip to main content

Dependency Injections

With dependency injections, dependencies of objects can be regulated at runtime. For example, if an object needs a reference to another object, it is provided by n2n.

Magic Methods​

Dependency injections are implemented in n2n via magic methods. A typical magic method is _init(), which can be implemented for example in controllers or [Thomas, I need a link here]Lookupables[/Thomas, I need a link here].

class ExampleController extends ControllerAdapter {
private $em;
private $mc;

private function _init(EntityManager $em, MessageContainer $mc) {
$this->em = $em;
$this->mc = $mc;
}
}

An _init() method is private and is typically executed when the object is instantiated. If you want to use dependency injections for other objects as well, you can manually instruct n2n via n2n\core\N2nContext::magicInit($object) to execute _init() for these objects.

class ExampleController extends ControllerAdapter {

public function index(N2nContext $n2nContext) {
$exampleModel = new ExampleModel();
$n2nContext->magicInit($exampleModel);
}
}

Available Types​

The following types can be used with dependency injections. For most types n2n also offers a static access option. If possible, however, you should refrain from using it, as this can make creating automated tests more difficult.

TypeStatic access
n2n\web\http\Requestn2n\N2N::getCurrentRequest()
n2n\web\http\Responsen2n\N2N::getCurrentResponse()
n2n\l10n\DynamicTextCollection
n2n\core\N2nContextn2n\N2N::getN2nContext()
n2n\core\Module
n2n\model\LookupManagern2n\N2N::getLookupManager()
n2n\l10n\Localen2n\N2N::getN2nContext()->getLocale()Current locale
n2n\core\MessageContainern2n\N2N::getMessageContainer()
Implementations of n2n\model\Lookupablen2n\N2N::getLookupManager()->lookup($className)