php购物车类的简单实现

Eddy 发布于2012-12-21 12:16:21 分类: 网站相关 已浏览loading 网友评论0条 我要评论


php购物车类的简单实现:

<?php
/*
 * 基于session(也可以存入数据库实现)实现的购物车
 * 全局有效性
 * 单例模式
 */
final class shopcartTool {
	private static $ins = null;
	private $items =array();
	
	private function __construct(){
		//构造函数
	}
	private function __clone(){
		//
	}
	private static function getIns(){
		if (!(self::$ins instanceof self)) {
			self::$ins = new self();
		}
		return self::$ins;
	}
	//获取购物车
	public static function getCart(){
		if(!isset($_SESSION['cart']) || !($_SESSION['cart'] instanceof self)){
			$_SESSION['cart'] = self::getIns();
		}
		return $_SESSION['cart'];
	}
	//添加商品
	public function addItem($id,$name,$price,$num=1){
		if(!$this->hasItem($id)){
		$item=array();
		$item['id']=$id;
		$item['name']=$name;
		$item['num']=$num;
		$item['price']=$price;
		$this->items[$id]=$item;
		}else{
			$this->modifyNum($id, $num);
		}
	}
	//删除商品
	public function deleteItem($id){
		if($this->hasItem($id)){
			unset($this->items[$id]);
		}
	}
	//修改商品数量
	public function modifyNum($id,$num){
		if($this->hasItem($id)){
			$this->items[$id]['num']+=$num;
		}
	}
	//商品数量加/减1
	public function changeOne($id,$add=true){
		if($this->hasItem($id)){
			if($add){
				++$this->items[$id]['num'];
			}else{
				--$this->items[$id]['num'];
				if($this->items[$id]['num']==0){
					$this->deleteItem($id);
				}
			}
		}
	}
	//清空购物车
	public function clearCart(){
		$this->items=array();
	}
	//获取购物车商品类别总数
	public function getItemsNum(){
		return count($this->items);
	}
	//获取购物车商品总数
	public function getNum(){
		$amount = 0;
		if($this->getItemsNum()==0){
			return $amount;
		}
		foreach ($this->items as $v){
			$amount +=$v['num'];
		}
		return $amount;
	}
	//获取购物车商品总金额
	public function getAmount(){
		$amount = 0.0;
		if($this->getItemsNum()==0){
			return $amount;
		}
		foreach ($this->items as $v){
			$amount +=$v['num']*$v['price'];
		}
		return $amount;
	}
	//判断商品是否已存在
	public function hasItem($id){
		return array_key_exists($id, $this->items);
	}
}
/*测试
session_start();
$cart = shopcartTool::getCart();
$cart->addItem(1,'test',3.26);
$cart->addItem(2,'test2',33.26);
$cart->changeOne(1);
echo $cart->getAmount(),'<br />';
echo $cart->getItemsNum(),'<br />';
echo $cart->getNum(),'<br />';
var_dump($cart);*/

已经有(0)位网友发表了评论,你也评一评吧!
原创文章如转载,请注明:转载自Eddy Blog
原文地址:http://www.rrgod.com/webdesign/863.html     欢迎订阅Eddy Blog

记住我的信息,下次不用再输入 欢迎给Eddy Blog留言