您可能对命令模式感兴趣。
你如何实现它取决于你——或者你正在使用的框架。
但这些模式通常会叠加。因此,也要好好阅读“周边”模式,以便能够就实际实现(或选择现有库)做出好的选择。
完全非正式的:
<?php
function foo($a, $b) {
return 'foo#'.($a+$b);
}
function bar($a,$b,$c) {
return 'bar#'.($a-$b+$c);
}
$cmds = array();
$cmds[] = function() { return foo(1,2); };
$cmds[] = function() { return bar(1,2,3); };
$cmds[] = function() { return bar(5,6,7); };
$cmds[] = function() { return foo(9,7); };
$s = new stdClass; $s->x = 8; $s->y = 8;
$cmds[] = function() use($s) { return foo($s->x,$s->y); };
// somewhere else....
foreach($cmds as $c) {
echo $c(), "\n";
}
或类似的东西
<?php
interface ICommand {
public function /* bool */ Execute();
}
class Foo implements ICommand {
public function __construct($id) {
$this->id = $id;
}
public function Execute() {
echo "I'm Foo ({$this->id})\n";
return true;
}
}
class Bar implements ICommand {
public function __construct($id) {
$this->id = $id;
}
public function Execute() {
echo "I'm Bar ({$this->id})\n";
return true;
}
}
$queueCommands = new SplPriorityQueue();
$queueCommands->insert(new Foo('lowPrio'), 1);
$queueCommands->insert(new Foo('midPrio'), 2);
$queueCommands->insert(new Foo('highPrio'), 3);
$queueCommands->insert(new Bar('lowPrio'), 1);
$queueCommands->insert(new Bar('midPrio'), 2);
$queueCommands->insert(new Bar('highPrio'), 3);
// somewhere else....
foreach( $queueCommands as $cmd ) {
if ( !$cmd->execute() ) {
// ...
}
}
或者是其他东西 ...