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.
| Type | Static access | |
|---|---|---|
n2n\web\http\Request | n2n\N2N::getCurrentRequest() | |
n2n\web\http\Response | n2n\N2N::getCurrentResponse() | |
n2n\l10n\DynamicTextCollection | ||
n2n\core\N2nContext | n2n\N2N::getN2nContext() | |
n2n\core\Module | ||
n2n\model\LookupManager | n2n\N2N::getLookupManager() | |
n2n\l10n\Locale | n2n\N2N::getN2nContext()->getLocale() | Current locale |
n2n\core\MessageContainer | n2n\N2N::getMessageContainer() | |
Implementations of n2n\model\Lookupable | n2n\N2N::getLookupManager()->lookup($className) |