• Services

Module imports

It is possible to create classes within a module that can be accessed by other modules. This allows for code sharing without duplication, or without the need to use package managers. This document gives an example on how to set this up, based on the modules module-a and module-b.

Defining exports

In your module in which you want to export the class, add the following to your module.json file:

{
  "slug": "module-a",

  "exports": {
    "SharedClass": "lib/SharedClass.php"
  },

  // ...
}

We then need to define the class we want to export, so we create lib/SharedClass.php:

// Optional:
// When using $this->import() to receive this class,
// we manually need to set the correct include path
// (in this case the 'lib' directory) because we are
// using namespaces. This wouldn't be a problem if
// every class was in the same directory, using the
// same namespace.
if(isset($export)) {
    set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../');
}

// Define class:
// As this file might be included multiple times as it
// is being exported by the module, we need to check if
// the class isn't already defined, to make sure we don't
// get an error about redeclaration during runtime.
if(!class_exists('SharedClass', false)) {
    /**
     * A shared class that does something.
     */
    class SharedClass
    {

      public function woof() {
        echo 'Woof woof!';
      }

    }
}

// Export class instance
if(isset($export)) {
    // Create new instance
    $instance = new SharedClass();
    return $instance;
}

Importing a class

We now have defined our exported class, so let's use it in module-b. Anywhere in our controllers, we can now do:

$doggy = $this->import('module-a', 'SharedClass');

$doggy->woof();