简体   繁体   中英

How to include my custom library in Opencart 3

I want to add a custom library to my store without adding require statements everywhere I need this library.

For example, I have the following class

class SuperLibrary {
   function someMethod() {

   }
}

How can I include it without modifying framework files?

As far as you are using Opencart 3+ there is good news. Libraries are autoloaded if configured correctly.

As we may find in the sources of Opencart. Autoload functions are used:

spl_autoload_register('library');
spl_autoload_extensions('.php');

And the library function itself

function library($class)
{
    $file = DIR_SYSTEM . 'library/' . str_replace('\\', '/', strtolower($class)) . '.php';
    if (is_file($file)) {
        include_once(modification($file));

        return true;
    } else {
        return false;
    }
}

So to load your custom library:

  1. Create a .php file at <root>/system/library , in that case, we can give the following name - superlibrary.php

  2. Let's consider that our library class is a singleton. So in our file superlibrary.php let's define the simple class:

     class SuperLibrary { private static $inst; public static function getInstance() { static::$inst = null; if (static::$inst === null) { static::$inst = new static(); } return static::$inst; } private function __construct() { } public function someMethod() { var_dump("HELLO WORLD"); exit; } }
  3. Next, if you try to dump loaded classes, you won't find it in the list, because, we didn't use it anywhere in our code. Let's use it, for instance, in any controller:

     $superLib = SuperLibrary::getInstance(); $superLib->someMethod();
  4. If everything is set up correctly you should see the dumped output of the method.

I hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM