在我的项目中,我正在处理数据并处理结果。有一个抽象类,如下所示:
class AbstractInterpreter
{
public function interprete( $data )
{
throw new Exception('Abstract Parent, nothing implemented here');
}
}然后有各种不同的AbstractInterpreter实现
class FooInterpreter extends AbstractInterpreter
{
public function interprete( $data )
{
return "resultFoo";
}
}
class BarInterpreter extends AbstractInterpreter
{
public function interprete( $data )
{
return "resultBar";
}
}我的调用代码创建解释器并收集结果:
//this is the data we're working with
$data = "AnyData";
//create the interpreters
$interpreters = array();
$foo = new FooInterpreter();
$bar = new BarInterpreter();
$interpreters[] = $foo;
$interpreters[] = $bar;
//collect the results
$results = array();
foreach ($interpreters as $currentInterpreter)
{
$results[] = $currentInterpreter->interprete($data);
}我现在正在创建越来越多的解释器,代码变得很混乱.对于每个解释器,我需要添加一个特定的include_once(..),我必须实例化它并将其放入$interpreters中。
现在终于要问我的问题了:
是否可以自动包含和实例化特定目录中的所有解释器并将它们放入$interpreters__中?
在其他语言中,这可能是某种插件--概念:
我创建了不同的AbstractInterpreter实现,将它们放在一个特定的子目录中,然后软件自动使用它们。我不需要修改代码,代码一旦完成,就会加载解释器。
发布于 2012-12-13 22:55:54
我不知道它是否可以自动实现,但是您可以编写几行代码来获得相同的结果。
function includeInterpreters($path) {
$interpreters=array();
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) {
include_once($path.$file);
$fileNameParts=explode('.', $file);
$interpreters[]=new $fileNameParts[0];
}
closedir($dh);
}
return $interpreters;
}
$interpreters= includeInterpreters('/path/plugins');将类文件命名为InterpreterName.php并放到相同的目录中,例如插件
是的,这看起来很乱。
https://stackoverflow.com/questions/13869781
复制相似问题