这个名字很糟糕,但我真的不知道还能叫它什么。
我试图为我的网站做一个可扩展和模块化的插件系统。我需要能够访问存在于插件目录中的插件php文件,并能够访问它们的类来调用函数,例如获取插件应该显示的html内容等等。
下面是我试图实现的一个半伪代码示例,但如何实际任意加载插件是我被卡住的地方(PluginLoader.php)。
-Max
//BasePlugin.php
abstract class BasePlugin
{
public function displayContent()
{
print "<p>Base Plugin</p>";
}
};
//ExamplePlugin.php -> In specific plugin directory.
require('../BasePlugin.php');
class ExamplePlugin extends BasePlugin
{
public static function Instance()
{
static $inst = null;
if ($inst === null) {
$inst = new ExamplePlugin();
}
return $inst;
}
public function displayContent()
{
print "<p>Example Plugin</p>";
}
}
//PluginLoader.php
foreach($pluginFile : PluginFilesInDirectory) { // Iterate over plugin php files in plugin directory
$plugin = GetPlugin($pluginFile); // Somehow get instance of plugin.
echo plugin->displayContent();
}
发布于 2018-06-04 06:45:04
我猜在这里,但在我看来你需要:
因此,您可能希望执行以下操作
$pluginDir = 'your/plugin/directory/' ;
$plugins = glob($pluginDir . '*.php') ;
foreach($plugins as $plugin) {
// include the plugin file
include_once($plugin) ;
// grab the class name from the plugin's file name
// this finds the last occurrence of a '/' and gets the file name without the .php
$className = substr($plugin,strrpos($plugin,'/') + 1, -4) ;
// create the instance and display your test
$aPlugin = $className::Instance() ;
$aPlugin->displayContent() ;
}
可能有一种更干净的方法来做这件事,但这将准备好您的目录,获得插件的代码,并实例化每个插件。之后如何管理/引用它们取决于插件如何在应用程序中注册。
https://stackoverflow.com/questions/50671411
复制相似问题