Jump to content

How to make a custom class globally available


chrizz
 Share

Recommended Posts

I have a module (autoload: true) which uses a custom class. If it would be only relevant for templates, _init.php would be the way to go but due to autoload functionality I need the class also to be availabel in the backend - this is where _init.php stops working.

If the class is declared in config.php it works fine - but is this the recommended way or is there a better solution for this?

Link to comment
Share on other sites

Hi @chrizz, personally I load all my custom classes through an autoloader called in config.php. For this purpose you can also consider ready.php.

However If the custom class is associated only to a specific module (it will be used only when this module is installed) I think you may consider to load it from within the module itself in init() or ready(). 

Link to comment
Share on other sites

You can assign your own API variables easily:

// MyModule.module.php

class foo {
  public function bar() {
    return 'works!';
  }
}

class MyModule extends WireData implements Module {
  public static function getModuleInfo() {
    return [
      'title' => 'MyModule',
      'version' => '0.0.1',
      'summary' => '...',
      'autoload' => true,
    ];
  }

  public function init() {
    $this->wire->set('foo', new foo());
  }
}

giNSM9L.png

You could also just save this instance to $config->foo

$this->wire->config->foo = new foo();

FadFH1B.png

  • Like 4
Link to comment
Share on other sites

@bernhard, thats what I did as well - but then I ran into trouble because I needed to access the same class from a different module (autoloaded as well). And then it became tricky because I don't know any way to control the order of autoloading ? 

Link to comment
Share on other sites

  • 4 weeks later...

Hey @chrizz. I'm moving this thread to the "Module/Plugin Development" area of the forum. Please post all module development related questions there – the main "Modules" area is only intended for support threads of existing modules. Thanks!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...