我建议你把属于车逻辑的所有代码到一个类它自己的。然后,您可以使用它作为代码中的门面:
// initialize session for Cart
$_SESSION['cart'] || $_SESSION['cart'] = new Cart();
// fetch cart from session
$cart = $_SESSION['cart'];
然后通过提供车,提供你正在寻找的功能,无论是在一个简单的形式方法:
$cart->increadeByOne($item);
或者给予更加分化的水平的封装完全访问:
$cart->getItem($item)->getQuantity()->increaseBy($number);
最后的这个例子似乎是臃肿,但一般它的好,有一个基类Cart
这样你就可以贝特处理并测试您的操作。
然后,您可以绑定与您的GET请求:
if (isset($_GET['increase1']))
{
$cart->getItem($_GET['increase1'])->getQuantity->increaseByOne();
}
有些粗糙车和数量布局:
Class CartItemQuantity
{
private $item;
private $quantity = 0;
public function __construct(CartItem $item)
{
$this->item = $item;
}
public function increaseByOne()
{
$this->increaseBy(1);
}
public function decreaseByOne()
{
$this->quantity = max(0, $this->quantity - 1);
}
public function increaseBy($number)
{
$this->quantity = max(0, $this->quantity + $number);
}
public function getQuantity()
{
return $this->quantity;
}
public function setQuantity($quantity)
{
if (is_string($quantity) && ctype_digit($quantity))
{
$quantity = (int) $quantity;
}
if (!is_int($quantity))
{
throw new InvalidArgumentException('Not a valid quantity (%s).', $quantity);
}
$this->quantity = max(0, $quantity);
}
}
Class CartItem
{
private $quantity;
...
public function __construct()
{
$this->quantity = new CartItemQuantity($this);
...
}
public function getQuantity()
{
return $this->quantity;
}
}
Class CartItems
{
...
/**
* @return CartItem
*/
public function getItem($item)
{
...
return $item;
}
}
Class Cart
{
/**
* @var CartItems
*/
private $items;
...
public function increaseByOne($item)
{
$this->items->getItem($item)->getQuantity()->increaseByOne();
}
/**
* @return CartItem
*/
public function getItem($item)
{
return $this->items->getItem($item);
}
}
,而不是让你应该使用POST方法。 否则先搜索爬虫找到你的店铺将是第一个购买你所有的股票。 – 2012-02-25 13:48:44