What is the correct way to include plugin files in a plugin system

I created a plugin system, and I created everything in this system, except how I can include plugin files to execute it.

I am trying to create a method that includes plugin files to execute it.

- Firstly -:
A method that receives all the plugin files and starts with the word index , which indicates the main plugin file (for example, index-pluginName.php) and adds the path and file name to the array.

 public function getPluginFiles($plugin_folder) { $dir = opendir($plugin_folder); while ($files = readdir($dir)) { if ($files == '.' || $files == '..') continue; if (is_dir($plugin_folder.'/'.$files)) $this->getPluginFiles($plugin_folder.'/'.$files); if (preg_match('/^[index]+/i', $files)) { $this->plugins_path[$plugin_folder.'/'.$files] = $files; } } closedir($dir); } 

- Secondly -:
This method includes the entire main plug-in file to execute, and this method gets the path and file name of the plug-in from a previously created array.

 public function includePlugFiles() { $this->getPluginFiles($this->plugin_folder); foreach ($this->plugins_path as $dir=>$file) { include_once (dirname($dir)."/".$file); } } 

Also see the example code that exists in the plugin file:

 function test() { echo " This is first plugin <br/>"; } $plugin->addHook('top', test); // parameters(top=position, test=callback) 

Now, when I create an object instance for this form.

 $plugin = new plugin; $plugin->includePlugFiles(); 

But after all this, an error message appears

Fatal error: Call to a member function addHook() on a non-object in .... projects\plugins\index-test.php on line 7

This is line 7 code:

 $plugin->addHook('top', test); // parameters(top=position, test=callback) 

I know that the problem arises because the object will not be created. and the problem cannot create an object in every file of the main plugin.

+4
source share
1 answer

This is probably not the cleanest solution, but instead of trying to refer to the $plugin symbol (which goes beyond the scope of the plugin file), you can also do this:

 $this->addHook('top', test); 

Alternatively, you can explicitly create a link inside the includePlugFiles() method:

 public function includePlugFiles() { $plugin = $this; $this->getPluginFiles($this->plugin_folder); foreach ($this->plugins_path as $dir=>$file) { include_once (dirname($dir)."/".$file); } } 
0
source

Source: https://habr.com/ru/post/1435918/


All Articles