php实现委托
PHP 实现委托模式
委托模式(Delegate Pattern)是一种设计模式,允许一个对象将某些职责交给另一个对象处理。在 PHP 中,可以通过以下方式实现委托模式。
使用匿名函数(闭包)
PHP 的闭包功能可以方便地实现委托模式。通过将函数作为变量传递,可以动态改变行为。
$delegate = function($param) {
return "处理结果: " . $param;
};
$result = $delegate("测试数据");
echo $result; // 输出: 处理结果: 测试数据
通过对象方法委托
定义一个接口或抽象类,具体实现由委托对象完成。
interface TaskDelegate {
public function handle($data);
}
class ConcreteDelegate implements TaskDelegate {
public function handle($data) {
return "具体处理: " . $data;
}
}
class Delegator {
private $delegate;
public function __construct(TaskDelegate $delegate) {
$this->delegate = $delegate;
}
public function execute($data) {
return $this->delegate->handle($data);
}
}
$delegator = new Delegator(new ConcreteDelegate());
echo $delegator->execute("委托数据"); // 输出: 具体处理: 委托数据
使用魔术方法 __call
通过 __call 方法动态转发调用到委托对象。
class Delegate {
public function process($input) {
return "委托处理: " . $input;
}
}
class MainClass {
private $delegate;
public function __construct() {
$this->delegate = new Delegate();
}
public function __call($name, $arguments) {
if (method_exists($this->delegate, $name)) {
return call_user_func_array([$this->delegate, $name], $arguments);
}
}
}
$obj = new MainClass();
echo $obj->process("动态委托"); // 输出: 委托处理: 动态委托
使用 callable 类型提示
PHP 7.0+ 支持 callable 类型提示,可以更安全地传递可调用对象。

class TaskRunner {
public function execute(callable $delegate, $data) {
return $delegate($data);
}
}
$runner = new TaskRunner();
$result = $runner->execute(function($d) { return strtoupper($d); }, "hello");
echo $result; // 输出: HELLO
每种方法适用于不同场景,闭包方式适合简单逻辑,接口方式更规范,__call 适合动态代理,callable 类型提示则提供更好的类型安全。






