包括运行函数的PHP脚本?

时间:2012-09-21 23:57:59

标签: php

我希望创建一个类似程序的插件管理器,它启动一个循环,搜索'plugins'文件夹中的.php文件。我需要这个以某种方式在每个文件中运行一个名为main()的函数,然后运行其他函数。如果没有其他main()函数发生冲突,我怎么能做到这一点呢?还有更好的选择吗?

1 个答案:

答案 0 :(得分:1)

如果要使用函数,则可以命名它们。但对于像这样的东西,使用类。例如,每个插件可能有一个PluginConfiguration类,可以像PluginName\PluginConfiguration那样命名空间,也可以像PluginName_PluginConfiguration一样伪造。

然后你可以jsut instatiate这些类并调用例如:

class MyCool_Plugin implements PluginInterface {

  // note the interface wouldnt be absolutely necessary, 
  // but making an interface or abstract class for this would be a good idea
  // that way you can enforce a contractual API on the configuration classes

  public function __construct() {
     // do whatever here
  }

  public function main() {
     // do whatever here
  }
}

<强>更新

  

顺便说一下,'PluginInterface'会包括什么?

接口定义了必须类实现的所有方法(函数)。您可以使用它在implements该接口的任何类上强制执行最小API。根据您的描述,这将是方法main,尽管在开发过程中您可能会发现您需要/想要添加更多。

Interface PluginInterface {

   public function main();

}

您还可以使用类型提示来强制执行特定的方法签名。例如,假设您总是想要将插件加载到插件中的Application实例注入,以便它可以注册内容或设置其他内容。在这种情况下,您可以这样做:

Interface PluginInterface {

   public function main(Application $app);

}