我刚刚开始使用依赖注入,我立即遇到了一个问题:我有两个相互依赖的类。
类是Basket和Shipping。在我的Basket类中,我有以下相关方法:
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类的一个实例。
我完全不知道如何解决这个循环依赖。提前感谢您的帮助。
更新在Shipping类中我也有这个方法:
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
);
}
我最终将Shipping
重命名为Shipping_Methods
,并创建了一个名为Customer_Shipping_Methods
的新类。本质上,Customer_Shipping_Methods
可以是Basket
类的一部分,但我宁愿把它分开。
@RyanLaBarre完全正确。我基本上是混合的方法,应该是在Basket
类与方法在我的Shipping_Methods
类。Shipping_Methods
应该只包含一般的运输数据方法,而不是特定于当前会话。
我认为什么让我,是Shipping_Methods
来源的数据从csv文件,而不是一个数据库表。一旦我开始把Shipping_Methods
看作只是另一个表,它就在我的脑海中闪现。
@rdlowrey这是非常好的建议。我将把我的会话全局立即到我的控制器!