【问题标题】:PHP e-commerce system circular dependency issuePHP电商系统循环依赖问题
【发布时间】:2011-12-09 05:42:04
【问题描述】:

我刚刚开始使用依赖注入,我立即遇到了一个问题:我有两个相互依赖的类。

类是篮子和运输。 在我的篮子类中,我有以下相关方法:

public function totalShipping()
{
    return $this->_shipping->rate();
}

public function grandTotal()
{
    return $this->totalProductsPrice() + $this->totalShipping();
}

public function totalWeight()
{
    $weight = 0;
    $products = $this->listProducts();
    foreach ($products as $product) {
        $weight += $product['product_weight'];
    }

    return ($weight == '') ? 0 : $weight;
}

$this->_shipping 是 Shipping 类的一个实例

在我的 Shipping 课程中,我有以下相关方法:

public function rate()
{   
    if (isset($_SESSION['shipping']['method_id'])) {
        $methodId = $_SESSION['shipping']['method_id'];
        return $this->_rates[$methodId]['Shipping Price'];
    }

    // Method not set
    return NULL;
}

// Available Methods depend on country and the total weight of products added to the customer's basket. E.g. USA and over 10kg
public function listAvailableMethods()
{   
    $rates = array();

    if (isset($_SESSION['customer']['shipping_address']['country_code'])) {
        foreach ($this->_rates as $method_id => $rate) {
            if (($_SESSION['customer']['shipping_address']['country_code'] == $rate['Country']) && ($this->_basket->totalWeight() > $rate['Weight From']) && ($this->_basket->totalWeight() < $rate['Weight To'])) {
                $rates[$method_id] = $rate;
            }
        }
    }

    return $rates;
}

$this-&gt;_basket 是 Basket 类的一个实例。

我完全不知道如何解决这种循环依赖。提前感谢您的帮助。

更新

在我的运输类中,我也有这种方法:

public function setMethod($method_id)
{
    // A check to make sure that the method_id is one of the provided methods
    if ( !array_key_exists($method_id, $this->listAvailableMethods()) ) return false;

    $_SESSION['shipping'] = array(
        'method_id' => $method_id
    );
}

【问题讨论】:

  • 作为一种解决方法,我已将 listAvailableMethods() 更改为 listAvailableMethods(Basket $basket) 并在此时而不是在类初始化时传递了 Basket。这可以接受吗?
  • 在我看来,listAvailableMethods 函数属于 Basket 类,而不是 Shipping 类。然后,使用费率的篮子会有一个明确的关系,但绝不会反过来。
  • @RyanLaBarre 起初我认为这是一个绝妙的解决方案,但后来我意识到我的航运类中的 setMethod 函数使用了 listAvailableMethods() 函数:(
  • 我想我可以将这两个函数都移过来.. 看起来很奇怪。
  • 可以把那个也移到篮子里吗?它们看起来都是依赖于特定用户的会话信息并与他们自己的购物篮/个人信息的内容相关的功能。我想最好将 Shipping 类限制为不特定于当前会话的一般 Shipping 数据。它应该只为传递给它的任何给定的运输方式和地址返回正确的费率等,而不需要在其中实例化任何特定的实例。

标签: php oop dependency-injection circular-dependency loose-coupling


【解决方案1】:

我最终将Shipping 重命名为Shipping_Methods,并创建了一个名为Customer_Shipping_Methods 的新类。本质上,Customer_Shipping_Methods 可能是 Basket 类的一部分,但我宁愿将其分开。

@RyanLaBarre 完全正确。我基本上是在将应该在 Basket 类中的方法与我的 Shipping_Methods 类中的方法混合在一起。 Shipping_Methods 应该只包含不特定于当前会话的一般运输数据方法。

我认为让我感到震惊的是,Shipping_Methods 从 csv 文件而不是数据库表中获取数据。当我开始将Shipping_Methods 视为另一张桌子时,这一切都在我脑海中浮现。

@rdlowrey 这是非常好的建议。我将立即将我的会话全局变量放入我的控制器中!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 2021-01-25
    相关资源
    最近更新 更多