Classloader

The classloader is provided by Nextcloud and loads all your classes automatically. See the composer section if you want to include and autoload 3rd party libraries.

PSR-4 autoloading

Nextcloud uses a PSR-0 autoloader. The namespace \OCA\MyApp is mapped to /apps/myapp/lib/. Afterwards normal PSR-4 rules apply, so a folder is a namespace section in the same casing and the class name matches the file name.

If your appid can not be turned into the namespace by uppercasing the first character, you can specify it in your appinfo/info.xml by providing a field called namespace. 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:

<?xml version="1.0"?>
<info>
   <namespace>MyBeautifulApp</namespace>
   <!-- other options here ... -->
</info>

A second PSR-4 root is available when running tests. \OCA\MyApp\Tests is thereby mapped to /apps/myapp/tests/.

Replacing Nextcloud’s autoloader

Nextcloud’s autoloader for apps is flexible and robust but not always the fastest. You can improve the loading speed of your app by shipping and optimizing a Composer class loader with the app.

First of all, familiarize yourself with the Composer autoloader optimization options and how they work. (Authoritative) class maps are a good fit for Nextcloud apps.

Once Composer is set up and class maps have been dumped, you can replace the generic Nextcloud class loader with the Composer class loader. This is done by placing a file at composer/autoload.php. If Nextcloud finds this file for an app, no generic class loader will be registered. The following contents will wire the file to Composer’s generated autoloader.php file:

composer/autoload.php
<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

Note

Make sure the auto loader is generated at release time and all files are included in the release tarball