您的位置:首页 > 编程语言 > PHP开发

PHP购物车实现的思路

2010-11-24 17:39 471 查看
<?php
/**
* 商品的基本属性,只要用户添加一任意一件商品放购物车,该类就会被实例化一次并且对象会保存到购物车里。
* @author hojust
*
*/
class Product extends Model{
//表名
protected $_table="product";
//主键名
protected $_key="id";

//当前用户购买该商品的数量
private $quantity=1;

private $id; //商品ID
private $name; //名称
private $price; //价格
private $image;
/**
* 根据商品ID从数据库中获取相关商品信息
* @param $product_id 商品ID
*/
public function __construct($product_id){...}

/*
*如果购买相同商品,该商品的数量相应增加
*/
public function incrementQuantity($quantity=1){...}

/**
* 单个商品的价格(价格*数量)
* @return float
*/
public function getTotal(){...}

/**
* 获取缩略图片
*/
public function getSamllImage(){...}

public function getPrice() {...}

public function getName() {...}
...........
?>

<?php
/**
* 购物车类
* @author hojust
* 该购物车继承了PHP标准库的(ArrayObject)超类
* 它的主要功能就是把对象存放在一个protected类型的数组里面.在把购物车(Cart)对象保存到Session里
* 然后就可以能过Session获得购物车(Cart)对象,在通过用for或foreach输出所有商品对象
*
*/
class Cart extends ArrayObject{

//存放商品对象
protected $_product=array();

public function __construct(){
parent::__construct($this->_product);
}

/**
* 统计购物车里的所有商品的总价格
* @return float
*/
public function getCartTotal(){
$sum=0;
foreach($this as $product){
//每件商品的单价
$sum+=$product->getTotal();
}
return $sum;
}

/**
*当用户购买了相同商品时,不保存商品对象,而是在原来的商品数量加1
*@return boolean
*/
public function offsetSet($offset,$product){
if( $this->offsetExists($offset) ){
$this[$offset]->incrementQuantity(1);
return true;
}
parent:offsetSet($offset,$product);
}
}
?>

<?php
//把商品添加到购物车里是相当简单
$cart=new Cart();
$cart[1]=new Product(1);
$cart[2]=new Product(2);
$cart[2]=new Product(2); //当下标一样时,购物车不会存储该对象,而是在原以存在的商品数量上加1
$cart[3]=new Product(3);

//把商品对象从购物车里读出来
foreach( $cart as $product){
echo $product->getName();
echo $product->getPrice();
echo $product->getTotal();
}

echo $cart->getCartTotal();//所有商品的总价格。
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: