如果您想创建类似批处理的功能,请使用Command Pattern。
下面是该模式的一个非常简单的实现。这个想法是为您要调用的所有类提供统一的接口。每个类在批处理中封装一个操作:
interface BatchCommand
{
public function execute();
public function undo();
}
一个实现接口的类将是所有子类的指挥官:
class BatchCommander implements BatchCommand
{
protected $commands;
public function add(BatchCommand $command)
{
$this->commands[] = $command;
}
public function execute()
{
foreach($this->commands as $command) {
$command->execute();
}
}
public function undo()
{
foreach($this->commands as $command) {
$command->undo();
}
}
}
一个简单的命令可能如下所示:
class FileRename implements BatchCommand
{
protected $src;
protected $dest;
public function __construct($src, $dest)
{
$this->$src;
$this->dest;
}
public function execute()
{
rename($this->src, $this->dest);
}
public function undo()
{
rename($this->dest, $this->src);
}
}
你可以这样使用它:
$commander = new BatchCommander;
$commander->add(new FileRename('foo.txt', 'bar.txt'));
$commander->add(/* other commands */);
$commander->execute();
因为 BatchCommander 本身就是一个 BatchCommand,您可以轻松地将属于一起的批次堆叠到其他批次中,从而创建一个非常灵活的树形结构,例如
$batch1 = new BatchCommander;
$batch1->add(/* some command */);
$batch1->add(/* some other command */);
$batch2 = new BatchCommander;
$batch2->add(/* some command */);
$batch2->add(/* some other command */);
$main = new BatchCommander;
$main->add($batch1);
$main->add($batch2);
$main->execute();
在您的检查/测试上下文中,这意味着您可以将概念上属于的单个测试分组到一个测试套件中。您可以通过将一个套件堆叠到另一个套件中来创建测试套件的测试套件。
当然,您也可以为 BatchCommander 提供一个文件路径来检查实例化,并通过运行文件路径中的文件让它初始化所有 BatchCommands。或者传递一个 Factory 实例用于创建 Check 命令。
您不必为方法名称使用execute 和undo。如果需要,请将其命名为 check。如果您不需要,请忽略 undo。但是基本思想仍然保持不变:一个接口用于所有类的命令,无论它看起来像什么。随意适应。
一个略有不同的 UseCase 的替代方案是Chain of Reponsibility 模式。看看它是否也有用。