- /*
- * [原创] 用一个SESSION 实现在精典购物车
- * Author: Rock
- * Time: 2007-05-01
- * 因为一个小程序用到购物车,风有不小不过功能太多。
- * 今天就写了一个够自己用的购物车,精简型。
- * 大家如果想用,可以根据自己的需求修改功能。
- 1、添加商品
- 2、移除商品
- 3、修改商品数量
- 4、清空购物车
- 5、计算总额
- Array(
- [gId_1] => Array (
- [price] => 20
- [number] => 500
- )
- [gId_2] => Array (
- [price] => 20
- [number] => 20
- )
- }
- */
- ini_set('error_reporting', E_ALL);
- class MyCart{
- private $cartName ;
- public function __construct($cartName){
- session_start();
- $this->cartName = $cartName;
- if (!isset($_SESSION[$cartName])){
- $_SESSION[$cartName]=array();
- }
- }
- //add one product
- public function addItem($gId, $gNum = 1){
- if(empty($gId)) die('无此商品');
- if($this->isExistInCart($gId) == false){
- $_SESSION[$this->cartName][$gId]['number'] = $gNum;
- $_SESSION[$this->cartName][$gId]['price'] = $this->getGoodsPrice($gId);
- return true;
- }else{
- echo('已经在您的购物车中了!');
- return false;
- }
- }
- // delete one product
- public function delItem($gId){
- if(empty($gId)) die('删除失败,请重试');
- if($this->isExistInCart($gId) == false) return false;
- unset($_SESSION[$this->cartName][$gId]);
- return true;
- }
- //modify number of one product
- public function editItem($gId, $gNum){
- if(empty($gId)) die('编辑失败,请重试');
- if($this->isExistInCart($gId) == false) return false;
- $_SESSION[$this->cartName][$gId]['number'] = $gNum;
- return true;
- }
- //empty cart
- public function emptyCart(){
- //$_SESSION[$this->cartName] = NULL;
- unset($_SESSION[$this->cartName]);
- }
- // get total Price from Cart
- public function totalCartPrice(){
- $tPrice = 0;
- if(!isset($_SESSION[$this->cartName])) return $tPrice;
- $arrCart = $_SESSION[$this->cartName];
- if(is_array($arrCart) && count($arrCart) > 0){
- foreach($arrCart as $key=>$val){
- $tPrice += $val['number'] * $val['price'];
- }
- }
- return $tPrice;
- }
- // get total goods number from cart
- public function totalCartNumber(){
- $tNum = 0;
- if(!isset($_SESSION[$this->cartName])) return $tNum;
- $arrCart = $_SESSION[$this->cartName];
- if(is_array($arrCart) && count($arrCart) > 0){
- foreach($arrCart as $key=>$val){
- $tNum += $val['number'];
- }
- }
- return $tNum;
- }
- // check goodsid is or not exist in cart
- private function isExistInCart($gId){
- return isset($_SESSION[$this->cartName][$gId]) ? true : false ;
- }
- // get goods price from DB
- private function getGoodsPrice($gId){
- // extends for yourself
- return 10;
- }
- }
- // 测试开始
- $objCart = new MyCart('myCart');
- print_r($objCart);echo("\n");
- $objCart->addItem('10001', 3);
- $objCart->addItem('10002');
- $objCart->addItem('10003');
- $objCart->addItem('10004');
- $objCart->editItem('10003', 5);
- $objCart->delItem('10004');
- //$objCart->emptyCart();
- print_r($_SESSION);echo("\n");
- echo($objCart->totalCartPrice()."\n");
- echo($objCart->totalCartNumber()."\n");