php 类方法合并,php - PHP链式类方法与其他类合并 - 堆栈内存溢出

您可以尝试应用的概念是继承上的合成 。

一个解决方案可能是组成当前的Mold对象并传递两个插件实例,以便它可以在其方法上使用它们,如下所示:

class Mold {

public $current;

public function __construct(Plugin1 $plugin1, Plugin2 $plugin2) {

$this->plugin1 = $plugin1;

$this->plugin2 = $plugin2;

}

public function merge($first, $second) {

$this->current = $first . $second;

return $this;

}

public function phone() {

$this->current = '' . $this->current . '';

return $this;

}

public function __toString() {

return $this->current;

}

public function link() {

$this->plugin1->link();

return $this;

}

}

function mold() {

return new Mold(new Plugin1(), new Plugin2());

}

另一个解决方案是创建某种MoldHandler类,该类将Mold对象作为属性与其他插件一起使用,可以直接在其中使用。

public class MoldHanlder {

protected $mold;

protected $plugin1;

protected $plugin2;

public function __contruct($mold, $plugin1, $plugin2) {

$this->mold = $mold;

$this->plugin1 = $plugin1;

$this->plugin2 = $plugin2;

}

public function merge() {

$this->mold = $this->mold->merge();

return $this;

}

public function link() {

$foo = $this->plugin1->method();

return $this;

}

...

}

您也可以只实例化construct的类,但是如果您打算编写单元测试,则依赖注入是解决之道

我认为第一种方法更好,因为您避免自己重新编写Mold类的一些代码,这是不必要的

注意,这是一个非常原始的解决方案,只是为了让您更好地理解我会选择的想法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值