用特性或继承扩展PHP库


Extending PHP library with traits or inheritance?

作为一个软件开发人员,我想为我的客户提供一个扩展的库。不能更改库提供程序的原始库。

有几种方法可以做到这一点。我想到了性状,也想到了遗传。

假设在原始库中有一个类定义为:

class Super {}
第一种方法:使用traits: 扩展原始库
trait MyTrait {
    public function func() {
        echo "func in MyTrait'n";
    }
}
// Customer writes in his code:
class Sub1 extends Super {
    use MyTrait;
}
$sub1 = new Sub1;
$sub1->func();
第二种方法:使用继承扩展原始库:
class LibExtension extends Super {
    public function func() {
        echo "func in LibExtension'n";
    }
}
// Customer writes in his code:
class Sub2 extends LibExtension {
}
$sub2 = new Sub2;
$sub2->func();

在这种情况下使用性状和继承的优势是什么?哪种方法在哪种情况下更受限制?对于软件开发人员和客户来说,哪一个更灵活?

在开源和闭源领域,这些方法有什么不同吗?

对于这种情况是否有更好的方法?

很难推荐一种方法而不是另一种方法,但在许多情况下,组合是为最终用户提供灵活性的更合适的方法。

考虑你的特质样本:

trait MyTrait {
    public function func() {
        echo "func in MyTrait'n";
    }
}
// Customer writes in his code:
class Sub1 extends Super {
    use MyTrait;
}
$sub1 = new Sub1;
$sub1->func();

可以重写为:

interface FuncPrinterInterface
{
    public function funcPrint();
}
class FuncPrinter implements FuncPrinterInterface
{
    public function funcPrint()
    {
        echo "func in MyTrait'n";
    }
}
class UserClass
{
    /**
     * @var FuncPrinterInterface
     */
    protected $printer;
    /**
     * Sub1 constructor.
     *
     * @param FuncPrinterInterface $printer
     */
    public function __construct(FuncPrinterInterface $printer)
    {
        $this->printer = $printer;
    }
    public function doSomething()
    {
        $this->printer->funcPrint();
    }
}
$sub1 = new UserClass(new FuncPrinter());
$sub1->doSomething();