1

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

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

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 类的一个实例

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

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->_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
    );
}
4

1 回答 1

0

我最终重命名ShippingShipping_Methods,并创建了一个名为Customer_Shipping_Methods. 本质上Customer_Shipping_Methods可以是Basket课程的一部分,但我宁愿将其分开。

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

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

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

于 2011-12-09T07:52:23.180 回答