PHP+redis實(shí)現(xiàn)的購(gòu)物車單例類示例
本文實(shí)例講述了PHP+redis實(shí)現(xiàn)的購(gòu)物車單例類。分享給大家供大家參考,具體如下:
<?php
/**
* 購(gòu)物車單例類
*
* @author YING
* @param void
* @return void
*/
class CartSingleton
{
//定義一個(gè)靜態(tài)的私有變量
static private $_instance=null;
private $redis=null;
//私有化的構(gòu)造方法
private final function __construct()
{
//實(shí)例化
$this->redis=new Redis();
$this->redis->connect('127.0.0.1',6379);
}
//私有化的克隆方法
private function __clone()
{
}
//公有的靜態(tài)方法
static public function getInstance()
{
if(!(self::$_instance instanceof self)){
self::$_instance = new CartSingleton();
}
return self::$_instance;
}
/**
* 加入購(gòu)物車
*
* @author YING
* @param userId goodsName goodsId 用戶id 商品名稱 商品id
* @return int
*/
public function addCart($userId,$goodsName,$goodsId)
{
$hashKey="user_".$userId; //hash鍵名
$key=$goodsId."_".$goodsName;//鍵名
//加入
return $this->redis->hIncrBy($hashKey,$key,1);
}
/**
* 單刪
*
* @author YING
* @param userId goodsId
* @return
*/
public function cartDelOne($userId,$goodsId)
{
$hashKey="user_".$userId; //hash鍵名
$key=$goodsId;//鍵名
//刪除
return $this->redis->hDel($hashKey,$key);
}
/**
* 清空購(gòu)物車
*
* @author YING
* @param userId
* @return void
*/
public function cartDelAll($userId)
{
$hashKey="user_".$userId; //hash鍵名
//刪除
return $this->redis->del($hashKey);
}
/**
* 購(gòu)物車列表
*
* @author YING
* @param userId
* @return void
*/
public function cartList($userId)
{
$hashKey="user_".$userId; //hash鍵名
//查詢數(shù)據(jù)
return $this->redis->hGetAll($hashKey);
}
}
//實(shí)例化類
$obj=CartSingleton::getInstance();
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php+redis數(shù)據(jù)庫(kù)程序設(shè)計(jì)技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP基本語(yǔ)法入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章
php對(duì)mongodb的擴(kuò)展(初出茅廬)
我們的php mongodb也能做mysql、sqlserver能做的幾乎所有功能,本文將詳細(xì)介紹2012-11-11
php數(shù)據(jù)入庫(kù)前清理 注意php intval與mysql的int取值范圍不同
php數(shù)據(jù)入庫(kù)前清理 注意php intval與mysql的int取值范圍不同,需要的朋友可以參考下。2010-12-12
通過PHP current函數(shù)獲取未知字符鍵名數(shù)組第一個(gè)元素的值
在開發(fā)中經(jīng)常遇到這樣問題,獲取數(shù)組第一個(gè)元素的值,如果是數(shù)字索引那還好,直接$array[0],如果鍵名是字符串,你又未知這個(gè)字符串呢?用current()函數(shù)就可以做到2013-06-06
PHP實(shí)現(xiàn)通過get方式識(shí)別用戶發(fā)送郵件的方法
這篇文章主要介紹了PHP實(shí)現(xiàn)通過get方式識(shí)別用戶發(fā)送郵件的方法,涉及php針對(duì)數(shù)據(jù)庫(kù)的讀取、判斷及session登陸的使用技巧,需要的朋友可以參考下2015-07-07
php實(shí)現(xiàn)的在線人員函數(shù)庫(kù)
ME之前用的..找到了.. 在線人員函數(shù)庫(kù)2008-04-04
PHP封裝XML和JSON格式數(shù)據(jù)接口操作示例
這篇文章主要介紹了PHP封裝XML和JSON格式數(shù)據(jù)接口操作,結(jié)合實(shí)例形式分析了php針對(duì)xml與json格式數(shù)據(jù)接口封裝相關(guān)操作技巧,需要的朋友可以參考下2019-03-03

