Dependency injection

The App Framework assembles the application by using a container based on the software pattern Dependency Injection. This makes the code easier to test and thus easier to maintain.

If you are unfamiliar with this pattern, watch the following video:

Dependency injection

Dependency Injection sounds pretty complicated but it just means: Don’t put new dependencies in your constructor or methods but pass them in. So this:

  1. <?php
  2. // without dependency injection
  3. class AuthorMapper {
  4. /** @var IDBConnection */
  5. private $db;
  6. public function __construct() {
  7. $this->db = new Db();
  8. }
  9. }

would turn into this by using Dependency Injection:

  1. <?php
  2. use OCP\IDBConnection;
  3. // with dependency injection
  4. class AuthorMapper {
  5. /** @var IDBConnection */
  6. private $db;
  7. public function __construct(IDBConnection $db) {
  8. $this->db = $db;
  9. }
  10. }

Using a container

Note

Please do use automatic dependency injection (see below). For most apps there is no need to register services manually.

Passing dependencies into the constructor rather than instantiating them in the constructor has the following drawback: Every line in the source code where new AuthorMapper is being used has to be changed, once a new constructor argument is being added to it.

The solution for this particular problem is to limit the new AuthorMapper to one file, the container. The container contains all the factories for creating these objects and is configured in lib/AppInfo/Application.php.

Nextcloud 20 and later uses the PSR-11 standard for the container interface, so working with the container might feel familiar if you’ve worked with other php applications before that also adhere to the convention.

To add the app’s classes simply open the lib/AppInfo/Application.php and use the registerService method on the container object:

  1. <?php
  2. namespace OCA\MyApp\AppInfo;
  3. use OCP\AppFramework\App;
  4. use OCA\MyApp\Controller\AuthorController;
  5. use OCA\MyApp\Service\AuthorService;
  6. use OCA\MyApp\Db\AuthorMapper;
  7. use Psr\Container\ContainerInterface;
  8. class Application extends App {
  9. /**
  10. * Define your dependencies in here
  11. */
  12. public function __construct(array $urlParams=array()){
  13. parent::__construct('myapp', $urlParams);
  14. $container = $this->getContainer();
  15. /**
  16. * Controllers
  17. */
  18. $container->registerService('AuthorController', function(ContainerInterface $c){
  19. return new AuthorController(
  20. $c->get('AppName'),
  21. $c->get('Request'),
  22. $c->get('AuthorService')
  23. );
  24. });
  25. /**
  26. * Services
  27. */
  28. $container->registerService('AuthorService', function(ContainerInterface $c){
  29. return new AuthorService(
  30. $c->get('AuthorMapper')
  31. );
  32. });
  33. /**
  34. * Mappers
  35. */
  36. $container->registerService('AuthorMapper', function(ContainerInterface $c){
  37. return new AuthorMapper(
  38. $c->get('ServerContainer')->getDatabaseConnection()
  39. );
  40. });
  41. }
  42. }

How the container works

The container works in the following way:

  • A request comes in and is matched against a route (for the AuthorController in this case)

  • The matched route queries AuthorController service from the container:

    1. return new AuthorController(
    2. $c->get('AppName'),
    3. $c->get('Request'),
    4. $c->get('AuthorService')
    5. );
  • The AppName is queried and returned from the base class

  • The Request is queried and returned from the server container

  • AuthorService is queried:

    1. $container->registerService('AuthorService', function(ContainerInterface $c){
    2. return new AuthorService(
    3. $c->get('AuthorMapper')
    4. );
    5. });
  • AuthorMapper is queried:

    1. $container->registerService('AuthorMappers', function(ContainerInterface $c){
    2. return new AuthorService(
    3. $c->get('ServerContainer')->getDatabaseConnection()
    4. );
    5. });
  • The database connection is returned from the server container

  • Now AuthorMapper has all of its dependencies and the object is returned

  • AuthorService gets the AuthorMapper and returns the object

  • AuthorController gets the AuthorService and finally the controller can be instantiated and the object is returned

So basically the container is used as a giant factory to build all the classes that are needed for the application. Because it centralizes all the creation of objects (the new Class() lines), it is very easy to add new constructor parameters without breaking existing code: only the __construct method and the container line where the new is being called need to be changed.

Use automatic dependency assembly (recommended)

In Nextcloud it is possible to build classes and their dependencies without having to explicitly register them on the container, as long as the container can reflect the constructor and look up the parameters by their type. This concept is widely known as auto-wiring.

How does auto-wiring work

Automatic assembly creates new instances of classes just by looking at the class name and its constructor parameters. For each constructor parameter the type or the argument name is used to query the container, e.g.:

  • SomeType $type will use $container->get(‘SomeType’)
  • $variable will use $container->get(‘variable’)

If all constructor parameters are resolved, the class will be created, saved as a service and returned.

So basically the following is now possible:

  1. <?php
  2. namespace OCA\MyApp;
  3. class MyTestClass {}
  4. class MyTestClass2 {
  5. public $class;
  6. public $appName;
  7. public function __construct(MyTestClass $class, $AppName) {
  8. $this->class = $class;
  9. $this->appName = $AppName;
  10. }
  11. }
  12. $app = new \OCP\AppFramework\App('myapp');
  13. $class2 = $app->getContainer()->get('OCA\MyApp\MyTestClass2');
  14. $class2 instanceof MyTestClass2; // true
  15. $class2->class instanceof MyTestClass; // true
  16. $class2->appName === 'appname'; // true
  17. $class2 === $app->getContainer()->get('OCA\MyApp\MyTestClass2'); // true

Note

$AppName is resolved because the container registered a parameter under the key ‘AppName’ which will return the app id. The lookup is case sensitive so while $AppName will work correctly, using $appName as a constructor parameter will fail.

How does it affect the request lifecycle

  • A request comes in
  • All apps’ routes.php files are loaded
    • If a routes.php file returns an array, and an appname/lib/AppInfo/Application.php exists, include it, create a new instance of \OCA\AppName\AppInfo\Application.php and register the routes on it. That way a container can be used while still benefitting from the new routes behavior
    • If a routes.php file returns an array, but there is no appname/lib/AppInfo/Application.php, create a new \OCP\AppFramework\App instance with the app id and register the routes on it
  • A request is matched for the route, e.g. with the name page#index
  • The appropriate container is being queried for the entry PageController (to keep backwards compatibility)
  • If the entry does not exist, the container is queried for OCA\AppName\Controller\PageController and if no entry exists, the container tries to create the class by using reflection on its constructor parameters

How does this affect controllers

The only thing that needs to be done to add a route and a controller method is now:

myapp/appinfo/routes.php

  1. <?php
  2. return ['routes' => [
  3. ['name' => 'page#index', 'url' => '/', 'verb' => 'GET'],
  4. ]];

myapp/appinfo/lib/Controller/PageController.php

  1. <?php
  2. namespace OCA\MyApp\Controller;
  3. class PageController {
  4. public function __construct($AppName, \OCP\IRequest $request) {
  5. parent::__construct($AppName, $request);
  6. }
  7. public function index() {
  8. // your code here
  9. }
  10. }

There is no need to wire up anything in lib/AppInfo/Application.php. Everything will be done automatically.

How to deal with interface and primitive type parameters

Interfaces and primitive types can not be instantiated, so the container can not automatically assemble them. The actual implementation needs to be wired up in the container:

  1. <?php
  2. namespace OCA\MyApp\AppInfo;
  3. class Application extends \OCP\AppFramework\App {
  4. /**
  5. * Define your dependencies in here
  6. */
  7. public function __construct(array $urlParams=array()){
  8. parent::__construct('myapp', $urlParams);
  9. $container = $this->getContainer();
  10. // AuthorMapper requires a location as string called $TableName
  11. $container->registerParameter('TableName', 'my_app_table');
  12. // the interface is called IAuthorMapper and AuthorMapper implements it
  13. $container->registerService('OCA\MyApp\Db\IAuthorMapper', function (ContainerInterface $c) {
  14. return $c->get('OCA\MyApp\Db\AuthorMapper');
  15. });
  16. }
  17. }

Predefined core services

The following parameter names and type hints can be used to inject core services instead of using $container->getServer()->getServiceX()

Parameters:

  • AppName: The app id
  • WebRoot: The path to the Nextcloud installation
  • UserId: The id of the current user

Types:

  • OCP\IAppConfig
  • OCP\IAppManager
  • OCP\IAvatarManager
  • OCP\Activity\IManager
  • OCP\ICache
  • OCP\ICacheFactory
  • OCP\IConfig
  • OCP\AppFramework\Utility\IControllerMethodReflector
  • OCP\Contacts\IManager
  • OCP\IDateTimeZone
  • OCP\IDBConnection
  • OCP\Diagnostics\IEventLogger
  • OCP\Diagnostics\IQueryLogger
  • OCP\Files\Config\IMountProviderCollection
  • OCP\Files\IRootFolder
  • OCP\IGroupManager
  • OCP\IL10N
  • OCP\ILogger
  • OCP\BackgroundJob\IJobList
  • OCP\INavigationManager
  • OCP\IPreview
  • OCP\IRequest
  • OCP\AppFramework\Utility\ITimeFactory
  • OCP\ITagManager
  • OCP\ITempManager
  • OCP\Route\IRouter
  • OCP\ISearch
  • OCP\ISearch
  • OCP\Security\ICrypto
  • OCP\Security\IHasher
  • OCP\Security\ISecureRandom
  • OCP\IURLGenerator
  • OCP\IUserManager
  • OCP\IUserSession

How to enable it

To make use of this new feature, the following things have to be done:

  • appinfo/info.xml requires to provide another field called namespace where the namespace of the app is defined. The required namespace is the one which comes after the top level namespace OCA\, e.g.: for OCA\MyBeautifulApp\Some\OtherClass the needed namespace would be MyBeautifulApp and would be added to the info.xml in the following way:

    1. <?xml version="1.0"?>
    2. <info>
    3. <namespace>MyBeautifulApp</namespace>
    4. <!-- other options here ... -->
    5. </info>
  • appinfo/routes.php: Instead of creating a new Application class instance, simply return the routes array like:

    1. <?php
    2. return ['routes' => [
    3. ['name' => 'page#index', 'url' => '/', 'verb' => 'GET'],
    4. ]];

Note

A namespace tag is required because you can not deduce the namespace from the app id

Which classes should be added

In general all of the app’s controllers need to be registered inside the container. Then the following question is: What goes into the constructor of the controller? Pass everything into the controller constructor that matches one of the following criteria:

  • It does I/O (database, write/read to files)
  • It is a global (e.g. $_POST, etc. This is in the request class by the way)
  • The output does not depend on the input variables (also called impure function), e.g. time, random number generator
  • It is a service, basically it would make sense to swap it out for a different object

What not to inject:

  • It is pure data and has methods that only act upon it (arrays, data objects)
  • It is a pure function