search
HomeBackend DevelopmentPHP Tutorial PHP购物车种,移植于CodeIgniter

PHP购物车类,移植于CodeIgniter

<?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) 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;
			}
		}
	}
}
?>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools