添加相同选项时增加数量
我已经成功实现了 Cart
Basket 的 OOP
一个项目包含 1 个或多个选项。
如果我再次添加相同的 OptionID,那么数量应该增加,而不是创建另一个 Option 对象。那怎么办呢?
如果我再次添加相同的 ItemID,它应该拒绝创建另一个 Item
对象。
还有我的OOP好吗?
class Cart {
public $item = array();
public function addItem($id) {
$item = new Item();
$item->setItem($id);
$this->item[] = $item;
return $item;
}
}
class Item {
private $id = array();
private $option = array();
public function setItem($id) {
$this->id = $id;
return $this;
}
public function addOption($id) {
$option = new Option();
$option->setOption($id);
$this->option[] = $option;
}
}
class Option {
private $quantity;
private $id;
public function setOption($id) {
$this->quantity = 1;
$this->id = $id;
return $this;
}
}
$cart = new Cart();
//ItemID 10
$item = $cart->addItem(10);
//OptionID
$item->addOption(11);
$item->addOption(22);
$item->addOption(22); //should increase quantity
//It should not create another object because we already have Item Object of ItemID10
$item = $cart->addItem(10);
$Shop = $cart;
echo "<pre>";
print_r($Shop);
echo "</pre>";
I have managed to implement OOP of Cart
Basket
An Item contain 1 or more options.
If I add same OptionID again then the number of quantity should increase rather than creating another Option
Object. How can that be done?
If I add same ItemID again, it should refuse to create another Item
object.
Also is my OOP is good?
class Cart {
public $item = array();
public function addItem($id) {
$item = new Item();
$item->setItem($id);
$this->item[] = $item;
return $item;
}
}
class Item {
private $id = array();
private $option = array();
public function setItem($id) {
$this->id = $id;
return $this;
}
public function addOption($id) {
$option = new Option();
$option->setOption($id);
$this->option[] = $option;
}
}
class Option {
private $quantity;
private $id;
public function setOption($id) {
$this->quantity = 1;
$this->id = $id;
return $this;
}
}
$cart = new Cart();
//ItemID 10
$item = $cart->addItem(10);
//OptionID
$item->addOption(11);
$item->addOption(22);
$item->addOption(22); //should increase quantity
//It should not create another object because we already have Item Object of ItemID10
$item = $cart->addItem(10);
$Shop = $cart;
echo "<pre>";
print_r($Shop);
echo "</pre>";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果购物车中只能有一件具有唯一 id 的商品 - 那么请像这样重写 addItem() 方法:
addOption() 方法也是如此:
当然,您应该在 Option 中实现 setQuantity() 和 getQuantity() 方法班级。
希望这有帮助。
If you can have only one item with the unique id in the cart - then rewrite the addItem() method like this:
The same is with addOption() method:
And of course you should implement setQuantity() and getQuantity() methods in Option class.
Hope this helps.
部分重写了代码并进行了测试:
Partialy rewrote the code and tested: