在Drupal 8上包含PHP库

I have a class, and I want to be able to use it on the CMS, not depending on any module, for example because I want to keep it updated by git and use it not only in Drupal projects:

<?php

namespace MyPackage;

class MyClass {

    public static function myFunction($message) {
        file_put_contents('./file.log', $message, FILE_APPEND);
    }

}

The class lives inside the libraries/ folder of the drupal website, its path being: /libraries/MyPackage/MyClass.php Then I try to use it somewhere, e.g.,

\MyPackage\MyClass::myFunction("hey from myfunction!");

But the class is not reachable:

Error: Class 'MyPackage\MyClass' not found in ...

Also tried the other package path convention, placing the class in

/libraries/mypackage/src/MyPackage/MyClass.php

with no luck.

Where should I put my PHP class? Something wrong with the path? Something wrong with the naming convention? I almost tried everything, except the correct way of course.

You should try it with

use MyPackage\MyClass\MyClass::myFunction("Hey from my function");

MyPackage\MyClass is your namespace and MyPackage\MyClass\MyClass is your full class reference.

Seems like the only way to do this on Drupal 8 is through the composer dependency manager, which consists of the following steps:

  1. Creating your library with composer
  2. Compile and upload it on Packagist
  3. Use on your Drupal instance as other dependencies