您可以尝试应用的概念是继承上的合成 。
一个解决方案可能是组成当前的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类的一些代码,这是不必要的
注意,这是一个非常原始的解决方案,只是为了让您更好地理解我会选择的想法