这是"准备/存储函数调用"*的最佳方式,在稍后的点上,实际执行它?
(*参数数目未定)
我现在拥有的:
function addCall($className, [$parameter [, $parameter ...]])
{
$this->calls[] = func_get_args();
}
那么我将做:
foreach($this->calls as $args)
{
$r = new ReflectionClass(array_shift($args));
$instances[] = $r->newInstanceArgs($args);
}
在我看来不是很面向对象,包括"参数数量未定"的特征
我如何改进我的代码?
thank you in advance
您可能对Command模式感兴趣。
如何实现它取决于你——或者你正在使用的框架。
但这些模式通常会累积起来。因此,也要好好阅读"周围"模式,以便能够在实际实现(或选择现有库)方面做出正确的选择。
完全非正式的:
<?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() ) {
// ...
}
}