PHP插件加载器,它在特定目录中创建插件实例,并实现插件接口


PHP Plugin loader which creates instance of plugins in a specific directory and which impelements plugin interface

我如何用PHP创建一个实例,所有实现插件接口的插件,并保存在一个特定的插件目录

我在c#中做了一些类似的事情

Assembly assembly = Assembly.LoadFrom(pFileName);
foreach (Type type in assembly.GetTypes()){
if (type.IsPublic){
if (!type.IsAbstract){           
Type typeInterface = type.GetInterface(pTypeInterface.ToString(), true);
if (typeInterface != null){
try{
object plugin = Activator.CreateInstance(pluginInterfaceType);

是否有一种方法来翻译这个在php?

实现这一点的最简单和最安全的方法是什么?

问候

作为一种动态语言,PHP使这变得容易得多。一旦将实际的类名作为字符串,就可以对其进行实例化。然后,只需检查实例是否实现了预期的接口:

$pluginClass = 'My_Plugin';
$instance = new $pluginClass();
if(!$instance instanceof My_Interface) {
    throw new Exception(get_class($instance) . ' does not implement My_Interface');
}

要加载类,你应该阅读PHP中的自动加载类。如果你想让所有的类在一个特定的插件文件夹中可用,你只需要require_once在该文件夹中的任何*.php文件