【发布时间】: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->_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