【问题标题】:PHP Plugin loader which creates instance of plugins in a specific directory and which impelements plugin interfacePHP 插件加载器,它在特定目录中创建插件实例并实现插件接口
【发布时间】:2011-07-06 16:13:41
【问题描述】:

我如何用 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 class plugins interface


    【解决方案1】:

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

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

    要加载课程,您应该阅读autoloading classes in PHP。如果你想让特定插件文件夹中的所有类都可用,你只需要在该文件夹中使用任何 *.php 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 2017-02-27
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多