Skip to content

Instantly share code, notes, and snippets.

@eznix86
Forked from DevPGSV/api.php
Created May 28, 2020 18:30
Show Gist options
  • Save eznix86/599ffa820275d3aab7e13958f3b39964 to your computer and use it in GitHub Desktop.
Save eznix86/599ffa820275d3aab7e13958f3b39964 to your computer and use it in GitHub Desktop.
Plugin System in php
<?php
class Api {
public function call($o) {
echo $o."<br>\n";
}
}
<?php
return 'ExamplePlugin';
class ExamplePlugin extends TB_Plugin {
public function ExamplePlugin($api) {
parent::__construct($api);
}
public function call() {
$this->api->call('Called from ExamplePlugin');
}
public function whatever() {
echo "Doing whatever from ExamplePlugin<br>\n";
}
}
<?php
return 'HelloWorldPlugin';
class HelloWorldPlugin extends TB_Plugin {
public function HelloWorldPlugin($api) {
parent::__construct($api);
}
public function call() {
$this->api->call('Hello world from HelloWorldPlugin');
}
}
<?php
require_once('pluginManager.php');
require_once('api.php');
$pm = new PluginManager(new Api());
foreach (glob('./*_Plugin.php') as $file) {
$pm->registerPlugin(require_once($file));
}
echo "<b>Call:</b><br>\n";
$pm->doCall();
echo "<br><br><b>Whatever:</b><br>\n";
$pm->doWhatever();
<?php
abstract class TB_Plugin {
protected $api;
public function TB_Plugin($api) {
$this->api = $api;
}
public function call() {}
public function whatever() {}
}
<?php
require_once('api.php');
require_once('plugin.php');
class PluginManager {
private $pluginList; // TB_Plugin[]
private $api;
public function PluginManager($api) {
$this->pluginList = [];
$this->api = $api;
}
public function registerPlugin($plugin) {
$this->pluginList[$plugin] = new $plugin($this->api);
}
public function doCall() {
foreach ($this->pluginList as $pluginName => $plugin) {
echo "(Executing whatever on plugin: ".$pluginName.")<br>\n";
$plugin->call();
}
}
public function doWhatever() {
foreach ($this->pluginList as $pluginName => $plugin) {
echo "(Executing whatever on plugin: ".$pluginName.")<br>\n";
$plugin->whatever();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment