`
d2hellen
  • 浏览: 104191 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

PHP购物车类,移植于CodeIgniter

    博客分类:
  • PHP
阅读更多

<?php
/**
 * 购物车程序 Modified by CodeIgniter
 *
 */
class cart {

	// 对产品ID和产品名称进行正则验证属性
	var $product_id_rules	= '\.a-z0-9_-';
	var $product_name_rules	= '\.\:\-_ a-z0-9'; // 考虑到汉字,该功能暂不使用

	// 私有变量
	var $_cart_contents	= array();


	/**
	 * 构造方法
	 *
	 */
	public function __construct()
	{
		if ($this->session('cart_contents') !== FALSE)
		{
			$this->_cart_contents = $this->session('cart_contents');
		}
		else
		{
			// 初始化数据
			$this->_cart_contents['cart_total'] = 0;
			$this->_cart_contents['total_items'] = 0;
		}
	}

	// --------------------------------------------------------------------

	/**
	 * 添加到购物车
	 *
	 * @access	public
	 * @param	array
	 * @return	bool
	 */
	function insert($items = array())
	{
		// 检测数据是否正确
		if ( ! is_array($items) OR count($items) == 0)
		{
			return FALSE;
		}

		// 可以添加一个商品(一维数组),也可以添加多个商品(二维数组)

		$save_cart = FALSE;
		if (isset($items['id']))
		{
			if ($this->_insert($items) == TRUE)
			{
				$save_cart = TRUE;
			}
		}
		else
		{
			foreach ($items as $val)
			{
				if (is_array($val) AND isset($val['id']))
				{
					if ($this->_insert($val) == TRUE)
					{
						$save_cart = TRUE;
					}
				}
			}
		}
		// 更新数据
		if ($save_cart == TRUE)
		{
			$this->_save_cart();
			return TRUE;
		}

		return FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * 处理插入购物车数据
	 *
	 * @access	private
	 * @param	array
	 * @return	bool
	 */
	function _insert($items = array())
	{
		// 检查购物车
		if ( ! is_array($items) OR count($items) == 0)
		{
			return FALSE;
		}

		// --------------------------------------------------------------------

		/* 前四个数组索引 (id, qty, price 和name) 是 必需的。
		   如果缺少其中的任何一个,数据将不会被保存到购物车中。
		   第5个索引 (options) 是可选的。当你的商品包含一些相关的选项信息时,你就可以使用它。
		   请使用一个数组来保存选项信息。注意:$data['price'] 的值必须大于0 
		   如:$data = array(
               'id'      => 'sku_123ABC',
               'qty'     => 1,
               'price'   => 39.95,
               'name'    => 'T-Shirt',
               'options' => array('Size' => 'L', 'Color' => 'Red')
            );
		*/

		if ( ! isset($items['id']) OR ! isset($items['qty']) OR ! isset($items['price']) OR ! isset($items['name']))
		{
			return FALSE;
		}

		// --------------------------------------------------------------------

		// 数量验证,不是数字替换为空
		$items['qty'] = trim(preg_replace('/([^0-9])/i', '', $items['qty']));
		// 数量验证
		$items['qty'] = trim(preg_replace('/(^[0]+)/i', '', $items['qty']));

		// 数量必须是数字或不为0
		if ( ! is_numeric($items['qty']) OR $items['qty'] == 0)
		{
			return FALSE;
		}

		// --------------------------------------------------------------------

		// 产品ID验证
		if ( ! preg_match("/^[".$this->product_id_rules."]+$/i", $items['id']))
		{
			return FALSE;
		}

		// --------------------------------------------------------------------

		// 验证产品名称,考虑到汉字,暂不使用
		/*
		if ( ! preg_match("/^[".$this->product_name_rules."]+$/i", $items['name']))
		{
			return FALSE;
		}
		*/

		// --------------------------------------------------------------------

		// 价格验证
		$items['price'] = trim(preg_replace('/([^0-9\.])/i', '', $items['price']));
		$items['price'] = trim(preg_replace('/(^[0]+)/i', '', $items['price']));

		// 验证价格是否是数值
		if ( ! is_numeric($items['price']))
		{
			return FALSE;
		}

		// --------------------------------------------------------------------

		// 属性验证,如果属性存在,属性值+产品ID进行加密保存在$rowid中
		if (isset($items['options']) AND count($items['options']) > 0)
		{
			$rowid = md5($items['id'].implode('', $items['options']));
		}
		else
		{
			// 没有属性时直接对产品ID加密
			$rowid = md5($items['id']);
		}
		
		// 检测购物车中是否有该产品,如果有,在原来的基础上加上本次新增的商品数量
		$_contents = $this->_cart_contents;
		$_tmp_contents = array();
		foreach ($_contents as $val)
		{
			if (is_array($val) AND isset($val['rowid']) AND isset($val['qty']) AND $val['rowid']==$rowid)
			{
				$_tmp_contents[$val['rowid']]['qty'] = $val['qty'];
			} else {
				$_tmp_contents[$val['rowid']]['qty'] = 0;
			}
		}
		// --------------------------------------------------------------------

		// 清除原来的数据
		unset($this->_cart_contents[$rowid]);

		// 重新赋值
		$this->_cart_contents[$rowid]['rowid'] = $rowid;

		// 添加新项目
		foreach ($items as $key => $val)
		{
			if ($key=='qty' && isset($_tmp_contents[$rowid][$key])) {
				$this->_cart_contents[$rowid][$key] = $val+$_tmp_contents[$rowid][$key];
			} else {
				$this->_cart_contents[$rowid][$key] = $val;
			}
		}

		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * 更新购物车
	 * 
	 * @access	public
	 * @param	array
	 * @param	string
	 * @return	bool
	 */
	function update($items = array())
	{
		// 验证
		if ( ! is_array($items) OR count($items) == 0)
		{
			return FALSE;
		}

		$save_cart = FALSE;
		if (isset($items['rowid']) AND isset($items['qty']))
		{
			if ($this->_update($items) == TRUE)
			{
				$save_cart = TRUE;
			}
		}
		else
		{
			foreach ($items as $val)
			{
				if (is_array($val) AND isset($val['rowid']) AND isset($val['qty']))
				{
					if ($this->_update($val) == TRUE)
					{
						$save_cart = TRUE;
					}
				}
			}
		}

		if ($save_cart == TRUE)
		{
			$this->_save_cart();
			return TRUE;
		}

		return FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * 处理更新购物车
	 *
	 * @access	private
	 * @param	array
	 * @return	bool
	 */
	function _update($items = array())
	{
		if ( ! isset($items['qty']) OR ! isset($items['rowid']) OR ! isset($this->_cart_contents[$items['rowid']]))
		{
			return FALSE;
		}

		// 检测数量
		$items['qty'] = preg_replace('/([^0-9])/i', '', $items['qty']);

		if ( ! is_numeric($items['qty']))
		{
			return FALSE;
		}

		if ($this->_cart_contents[$items['rowid']]['qty'] == $items['qty'])
		{
			return FALSE;
		}

		if ($items['qty'] == 0)
		{
			unset($this->_cart_contents[$items['rowid']]);
		}
		else
		{
			$this->_cart_contents[$items['rowid']]['qty'] = $items['qty'];
		}

		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * 保存购物车到Session里
	 *
	 * @access	private
	 * @return	bool
	 */
	function _save_cart()
	{
		unset($this->_cart_contents['total_items']);
		unset($this->_cart_contents['cart_total']);

		$total = 0;
		$items = 0;
		foreach ($this->_cart_contents as $key => $val)
		{
			if ( ! is_array($val) OR ! isset($val['price']) OR ! isset($val['qty']))
			{
				continue;
			}

			$total += ($val['price'] * $val['qty']);
			$items += $val['qty'];

			$this->_cart_contents[$key]['subtotal'] = ($this->_cart_contents[$key]['price'] * $this->_cart_contents[$key]['qty']);
		}

		$this->_cart_contents['total_items'] = $items;
		$this->_cart_contents['cart_total'] = $total;

		if (count($this->_cart_contents) <= 2)
		{
			$this->session('cart_contents', array());

			return FALSE;
		}
		$this->session('cart_contents',$this->_cart_contents);

		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * 购物车中的总计金额
	 *
	 * @access	public
	 * @return	integer
	 */
	function total()
	{
		return $this->_cart_contents['cart_total'];
	}

	// --------------------------------------------------------------------

	/**
	 * 购物车中总共的项目数量
	 *
	 *
	 * @access	public
	 * @return	integer
	 */
	function total_items()
	{
		return $this->_cart_contents['total_items'];
	}

	// --------------------------------------------------------------------

	/**
	 * 购物车中所有信息的数组
	 *
	 * 返回一个包含了购物车中所有信息的数组
	 *
	 * @access	public
	 * @return	array
	 */
	function contents()
	{
		$cart = $this->_cart_contents;

		unset($cart['total_items']);
		unset($cart['cart_total']);

		return $cart;
	}

	// --------------------------------------------------------------------

	/**
	 * 购物车中是否有特定的列包含选项信息
	 *
	 * 如果购物车中特定的列包含选项信息,本函数会返回 TRUE(布尔值),本函数被设计为与 contents() 一起在循环中使用
	 *
	 * @access	public
	 * @return	array
	 */
	function has_options($rowid = '')
	{
		if ( ! isset($this->_cart_contents[$rowid]['options']) OR count($this->_cart_contents[$rowid]['options']) === 0)
		{
			return FALSE;
		}

		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * 以数组的形式返回特定商品的选项信息
	 *
	 * 本函数被设计为与 contents() 一起在循环中使用
	 *
	 * @access	public
	 * @return	array
	 */
	function product_options($rowid = '')
	{
		if ( ! isset($this->_cart_contents[$rowid]['options']))
		{
			return array();
		}

		return $this->_cart_contents[$rowid]['options'];
	}

	// --------------------------------------------------------------------

	/**
	 * 格式化数值
	 *
	 * 返回格式化后带小数点的值(小数点后有2位),一般价格使用
	 *
	 * @access	public
	 * @return	integer
	 */
	function format_number($n = '')
	{
		if ($n == '')
		{
			return '';
		}

		$n = trim(preg_replace('/([^0-9\.])/i', '', $n));

		return number_format($n, 2, '.', ',');
	}

	// --------------------------------------------------------------------

	/**
	 * 销毁购物车
	 *
	 * 这个函数一般是在处理完用户订单后调用
	 *
	 * @access	public
	 * @return	null
	 */
	function destroy()
	{
		unset($this->_cart_contents);

		$this->_cart_contents['cart_total'] = 0;
		$this->_cart_contents['total_items'] = 0;

		$this->session('cart_contents', array());
	}
	
	// --------------------------------------------------------------------

	/**
	 * 保存Session
	 *
	 * 须有session_start();
	 *
	 * @access	private
	 * @return	bool
	 */
	function session($name = 'cart_contents',$value = NULL) {
		if ($name=='') $name = 'cart_contents';
		if ($value == NULL) {
			return @$_SESSION[$name];
		} else {
			if (!empty($value) && is_array($value)) {
				$_SESSION[$name] = $value;
				return TRUE;
			} else {
				return FALSE;
			}
		}
	}
}
?>
分享到:
评论

相关推荐

    php仿写CodeIgniter的购物车类.zip

    讲述了php实现仿写CodeIgniter的购物车类。分享给大家供大家参考。具体如下: 购物车基本功能: 1) 将物品加入购物车  2) 从购物车中删除物品  3) 更新购物车物品信息 【 1/-1】  4) 对购物车物品...

    PHP实现的购物车类实例

    根据提供的文件内容,可以看出实现的购物车类是基于CodeIgniter框架的购物车类进行仿写的。CodeIgniter是一个轻量级的PHP框架,它提供了一个简单但功能强大的 MVC(模型-视图-控制器)架构。在CodeIgniter中,可以...

    PHP框架之CodeIgniter留言板实例

    PHP框架之CodeIgniter留言板实例PHP框架之CodeIgniter留言板实例PHP框架之CodeIgniter留言板实例PHP框架之CodeIgniter留言板实例PHP框架之CodeIgniter留言板实例PHP框架之CodeIgniter留言板实例PHP框架之CodeIgniter...

    PHP敏捷开发CodeIgniter框架

    6. **会话管理与安全**:CodeIgniter的Session类提供了安全的会话管理,有助于跟踪用户状态。此外,框架内嵌的安全特性,如XSS过滤和防止SQL注入,有助于提升应用的安全性。 7. **对象与类库扩展**:开发者可以创建...

    php实现仿写CodeIgniter的购物车类

    根据给定的文件内容,我们可以总结出以下几点关于php仿写CodeIgniter购物车类的知识点: 1. **购物车类的基本结构**: - 构造函数:PHP类的构造函数`__construct`用于初始化购物车对象,通过`$_SESSION`来保持用户...

    php敏捷开发框架Codeigniter

    CodeIgniter是一个基于PHP的轻量级Web应用框架,它以高效、简洁和优雅而闻名。这个框架的主要目标是让开发者能够快速地构建高质量的PHP应用程序,而无需从头开始编写大量的基础代码。通过使用MVC(Model-View-...

    PHP开发框架CodeIgniter中文参考资料

    3. **PHP敏捷开发框架CodeIgniter.chm**:这份文档可能侧重于介绍CodeIgniter在敏捷开发中的应用,强调快速原型构建和迭代开发的能力。它可能会涵盖框架的灵活性、可扩展性,以及如何利用其内置库和插件加速开发进程...

    自己写的新浪微博API操作类【PHP,并且适用于codeigniter】

    自己写的新浪微博API操作类【PHP,并且适用于codeigniter】

    CodeIgniter

    在CodeIgniter中,模型类用来与数据库交互,执行查询和数据操作。 2. **视图(View)**:视图是用户看到并与其交互的界面。它们通常包含HTML、CSS和JavaScript,不过在CodeIgniter中,视图文件仅包含HTML结构,其他...

    codeigniter-debug-toolbar:这是从 Kohana 移植的 CodeIgniter 的原始调试工具栏的修改版本

    这是从 Kohana 移植的 CodeIgniter 的原始调试工具栏的修改版本版本 0.3(适用于 CodeIgniter 2.x 和 3.x) 版权 基于 Aaron Forsander 的 Kohana 调试工具栏 ( ) 0.1 由 quark ( ) 移植到 CodeIgniter 0.2 由 Kon...

    Codeigniter购物车类不能添加中文的解决方法

    Codeigniter框架中购物车类不能添加中文字符的问题,很大程度上是由于在处理产品名称的时候,通过正则表达式对产品名称进行了非中文字符的限制。在`system/libraries/Cart.php`文件中的一个方法中,产品名称被限制为...

    PHP 敏捷开发框架 CodeIgniter

    CodeIgniter提供了强大的表单验证类,可以轻松验证用户输入数据,确保数据安全。 **六、安全与加密** 1. 输入过滤,防止XSS攻击。 2. 输出 escaping,防止SQL注入。 3. 加密服务,用于存储敏感数据,如密码哈希。 ...

    PHP CodeIgniter中文手册

    **PHP CodeIgniter 中文手册** CodeIgniter(CI)是一个轻量级的PHP框架,专为构建高效、可扩展的Web应用而设计。它的设计理念是保持代码简洁、优雅,同时提供强大的功能,使得开发过程既快速又愉快。CI的核心特性...

    PHP 敏捷开发框架 CodeIgniter - 快速 Web 应用开发详解

    CodeIgniter的Active Record类提供了一种简洁的接口来执行数据库操作,如查询、插入、更新和删除。开发者无需编写复杂的SQL语句,而是通过面向对象的方式进行操作。 七、助手函数与库 CodeIgniter包含大量助手函数...

    PHP的一个用CodeIgniter做的留言板的例子

    CodeIgniter是一个基于MVC(Model-View-Controller)架构的PHP框架,它为开发者提供了一个高效、简单的方式来创建功能丰富的Web应用。本实例是一个使用CodeIgniter开发的留言板系统,适合初学者学习和理解PHP框架的...

    PHP敏捷开发框架CodeIgniter

    本书详细讲解了 CI 的一些主要特性。本书并不包含 CI 的所有内容和全部细节。...本书系统地讲解了 CodeIgniter 的主要特性,并配合相应的代码范例进行了详尽的解释,使你能够由浅入深地掌握 CodeIgniter。

    codeigniter分页类的使用

    CodeIgniter 分页类是框架中用于实现动态分页功能的一个工具类,它极大地简化了在Web应用中处理大量数据分页显示的过程。在CodeIgniter中,分页类允许开发者自定义分页链接的样式、每页显示的记录数以及URL路径等...

    php基于CodeIgniter框架

    PHP 基于 CodeIgniter 框架 CodeIgniter(CI)是一种 PHP 框架,旨在帮助开发者快速、简便地构建应用程序。CI 的出现是为了解决开发者在编写应用程序时遇到的问题,即希望写出运行状态良好的应用程序,同时也希望...

Global site tag (gtag.js) - Google Analytics