<?php
/**
* 笔记部分
* 购物车类
*
* 分析购物车
* 1、无论在本网站刷新了多少次页面,或者新增了多少个商品,都要求在查看购物车时,看到的都是同样的结果。
* 2、既然是全局有效,购物车的实例只能有一个
*
* 解决方法:单例模式
*
* 功能分析:
* 1、判断某商品是否存在
* 2、添加某商品
* 3、删除某商品
* 4、修改某商品数量
*
* 5、某商品+1
* 6、某商品-1
*
* 7、查询购物车的商品种类
* 8、查询购物车的商品数量
* 9、查询购物车里的商品总金额
* 10、返回购物车里的所有商品
*
* 11、清空购物车
*
*/
session_start();
Class Cart {
private static $ins = null;
private $items = array();
final protected function __construct(){
}
final protected function __clone(){
}
protected static function getIns () {
if( !(self::$ins instanceof self) ) {
self::$ins = new self();
}
return self::$ins;
}
//把购物车的单例对象放到session里
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)){ //如果商品已经存在,则直接加其数量
echo $id."已存在";
$this->incItem($id,$num);
return;
}
$this->items[$id] = array();
$this->items[$id]['name'] = $name;
$this->items[$id]['price'] = $price;
$this->items[$id]['num'] = $num;
}
//修改购物车中的某商品数量
//直接将某商品的数量改为$num
public function modNum ($id,$num) {
if(!$this->hasItem($id)){
return false;
}
$this->items[$id]['num'] = $num;
}
//商品数量增加1
public function incItem ($id,$num=1) {
if($this->hasItem($id)){
$this->items[$id]['num'] += $num;
}
}
//商品数量减少1
public function decItem ($id,$num=1) {
if($this->hasItem($id)){
$this->items[$id]['num'] -= $num;
}
//如果为0
if($this->items[$id]['num'] < 1){
$this->delItem($id);
}
}
//删除某商品
public function delItem ($id) {
unset($this->items[$id]);
}
//判断某商品是否存在
public function hasItem ($id) {
return array_key_exists($id, $this->items);
}
//查询商品的种类
public function getCnt () {
return count($this->items);
}
//查询购物车中商品的数量
public function getNum () {
if($this->getCnt() == 0) {
return 0;
}
$sum = 0;
foreach($this->items as $v){
$sum += $v['num'];
}
return $sum;
}
//查询购物车的所有商品总金额
public function getPrice () {
if($this->getCnt() == 0) {
return 0;
}
$price = 0.0;
foreach($this->items as $v){
$price += $v['num'] * $v['price'];
}
return $price;
}
//返回购物车中的所有商品
public function getAll () {
return $this->items;
}
//清空购物车
public function clearCart () {
$this->items = array();
echo "购物车被清空了";
}
}
// print_r(Cart::getCart());
$cart = Cart::getCart();
if(!isset($_GET['test'])){
$_GET['test'] = '';
}
if($_GET['test'] == 'addw'){
$cart->addItem(1,'王八',23.4,1);
echo '买了一只王八';
}
else if($_GET['test'] == 'addc'){
$cart->addItem(2,'汽车',2500.46,1);
echo '买了一辆汽车';
}
else if ($_GET['test'] == 'clear'){
$cart->clearCart();
} else {
echo "<pre>";
print_r($cart->getAll());
echo '共有'. $cart->getCnt() .'种'. $cart->getNum() .'个商品<br />';
echo '商品总价格'. $cart->getPrice() . '元。';
}
ThinkPHP 是一个免费开源的,快速、简单的面向对象的 轻量级PHP开发框架 ,创立于2006年初,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。并且拥有众多的原创功能和特性,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,已经成长为国内最领先和最具影响力的WEB应用开发框架,众多的典型案例确保可以稳定用于商业以及门户级的开发。