我目前正在为一个应用程序编写一组骨架类,首先是一个名为storelogic的基类,它包含税收规则、折扣规则等,类cart、order、quote等。将扩展storelogic,因为它们都将使用storelogic提供的同一组方法。
一旦这些核心类完成,我将通过扩展cart、order、quote和storelogic来实现它们,因为这些类的每个应用程序将根据我们不同的客户需求而有所不同。从父类重写方法很容易,但是在其子类扩展它们之前重写祖父母类似乎…不可能?我觉得我这样做是不对的…我认为像你这样更有经验的人也许能给我指明正确的方向。看看代码,看看你是怎么想的!

/* My core classes are something like this: */
abstract class StoreLogic
{
    public function applyDiscount($total)
    {
        return $total - 10;
    }
}

abstract class Cart extends StoreLogic
{
    public function addItem($item_name)
    {
        echo 'added' . $item_name;
    }
}

abstract class Order extends StoreLogic
{
    // ....
}

/* Later on when I want to use those core classes I need to be able to override
 * methods from the grandparent class so the grandchild can use the new overriden
 * methods:
 */
class MyStoreLogic extends StoreLogic
{
    public function applyDiscount($total) {
        return $total - 5;
    }
}

class MyOrder extends Order
{
    // ...
}

class MyCart extends Cart
{
    public $total = 20;

    public function doDiscounts()
    {
        $this->total = $this->applyDiscount($this->total);
        echo $this->total;
    }
}

$cart = new MyCart();
$cart->doDiscounts(); // Uses StoreLogic, not MyStoreLogic..

最佳答案

我认为你在这里遗漏了一个非常基本的逻辑

- MyCart extends Cart
- Cart extends StoreLogic

如果要使用MyStoreLogic,则应将cart定义为
 abstract class Cart extends MyStoreLogic

如果你不想那么你可以
$cart = new MyCart();
$cart->doDiscounts(new MyStoreLogic()); // output 15

类修改
class MyCart extends Cart {
    public $total = 20;
    public function doDiscounts($logic = null) {
        $this->total = $logic ? $logic->applyDiscount($this->total) : $this->applyDiscount($this->total);
        echo $this->total;
    }
}

07-24 13:52