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:

use OCP\IDBConnection;

// without dependency injection
class AuthorMapper {
  private IDBConnection $db;

  public function __construct() {
    $this->db = new Db();
  }
}

would turn into this by using Dependency Injection:

use OCP\IDBConnection;

// with dependency injection
class AuthorMapper {
  private IDBConnection $db;

  public function __construct(IDBConnection $db) {
    $this->db = $db;
  }
}

Controller injection

For controllers it’s possible to also have dependencies injected into methods.

lib/Controller/ApiController.php
<?php

namespace OCA\MyApp\Controller;

use OCP\IRequest;

class ApiController {
    public function __construct($appName, IRequest $request) {
        parent::__construct($appName, $request);
    }

    public function foo(FooService $service) {
        $service->foo();
    }

    public function bar(BarService $service) {
        $service->bar();
    }
}

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 IRegistrationContext::registerService method:

<?php

namespace OCA\MyApp\AppInfo;

use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootstrap;
use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\IDBConnection;

use OCA\MyApp\Controller\AuthorController;
use OCA\MyApp\Service\AuthorService;
use OCA\MyApp\Db\AuthorMapper;
use Psr\Container\ContainerInterface;

class Application extends App implements IBootstrap {

  public function __construct(array $urlParams = []){
    parent::__construct('myapp', $urlParams);
  }

  public boot(IBootContext $context): void {
    // ...
  }

  /**
   * Define your dependencies in here
   */
  public function register(IRegistrationContext $context): void {
    /**
     * Controllers
     */
    $context->registerService(AuthorController::class, function(ContainerInterface $c): AuthorController {
      return new AuthorController(
        $c->get('appName'),
        $c->get(Request::class),
        $c->get(AuthorService::class)
      );
    });

    /**
     * Services
     */
    $context->registerService(AuthorService::class, function(ContainerInterface $c): AuthorService {
      return new AuthorService(
        $c->get(AuthorMapper::class)
      );
    });

    /**
     * Mappers
     */
    $context->registerService(AuthorMapper::class, function(ContainerInterface $c): AuthorMapper {
      return new AuthorMapper(
        $c->get(IDBConnection::class)
      );
    });
  }
}

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:

    return new AuthorController(
      $c->get('appName'),
      $c->get(Request::class),
      $c->get(AuthorService::class)
    );
    
  • The appName is queried and returned from the base class

  • The Request is queried and returned from the server container

  • AuthorService is queried:

    $container->registerService(AuthorService::class, function(ContainerInterface $c): AuthorService {
      return new AuthorService(
        $c->get(AuthorMapper::class)
      );
    });
    
  • AuthorMapper is queried:

    $container->registerService(AuthorMappers::class, function(ContainerInterface $c): AuthorMapper {
      return new AuthorService(
        $c->get(IDBConnection::class)
      );
    });
    
  • 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.

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

Optional services

New in version 28.

If an injected dependency can’t be found or build, an exception is thrown. This can be avoided by using the a nullable type notation for a dependency:

namespace OCA\MyApp\MyService;

use Some\Service;

class MyService {
  public function __construct(private ?Service $service) {
  }
}

If \Some\Service exists and can be built, it will be injected. Else MyService will receive null.

Accessing the container from anywhere

Sometimes it can be hard to inject some service inside legacy code, in these cases you can use OCPServer::get(MyService::class). This should only be used as the last resort, as this makes your code more complicated to unit test and is considered an anti-pattern.