【问题标题】:Extending PHP library with traits or inheritance?使用特征或继承扩展 PHP 库?
【发布时间】:2015-10-12 18:15:39
【问题描述】:

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

有几种方法可以做到这一点。特征进入脑海,但也继承。

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

class Super {}

第一种方法:使用特征扩展原始库:

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();

在这种情况下,使用特征与继承有什么优势? 在哪种情况下哪种方法更受限制?作为软件开发人员或客户,哪一个给我更大的灵活性?

如果我们在开源或闭源领域,这些方法有什么不同吗?

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

【问题讨论】:

    标签: php inheritance architecture traits


    【解决方案1】:

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

    考虑你的特质样本:

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 2017-05-18
      • 1970-01-01
      相关资源
      最近更新 更多