服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - PHP+redis实现的购物车单例类示例

PHP+redis实现的购物车单例类示例

2019-06-21 14:10梦屿千寻-不忘初心 PHP教程

这篇文章主要介绍了PHP+redis实现的购物车单例类,涉及php连接、操作redis数据库及购物车功能相关定义与使用技巧,需要的朋友可以参考下

本文实例讲述了PHP+redis实现的购物车单例类。分享给大家供大家参考,具体如下:

<?php
/**
 * 购物车单例类
 *
 * @author YING
 * @param void
 * @return void
 */
class CartSingleton
{
  //定义一个静态的私有变量
  static private $_instance=null;
  private $redis=null;
  //私有化的构造方法
  private final function __construct()
  {
    //实例化
    $this->redis=new Redis();
    $this->redis->connect('127.0.0.1',6379);
  }
  //私有化的克隆方法
  private function __clone()
  {
  }
  //公有的静态方法
  static public function getInstance()
  {
    if(!(self::$_instance instanceof self)){
      self::$_instance = new CartSingleton();
    }
    return self::$_instance;
  }
  /**
   * 加入购物车
   *
   * @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);
  }
  /**
   * 清空购物车
   *
   * @author YING
   * @param userId
   * @return void
   */
  public function cartDelAll($userId)
  {
    $hashKey="user_".$userId; //hash键名
    //删除
    return $this->redis->del($hashKey);
  }
  /**
   * 购物车列表
   *
   * @author YING
   * @param userId
   * @return void
   */
  public function cartList($userId)
  {
    $hashKey="user_".$userId; //hash键名
    //查询数据
    return $this->redis->hGetAll($hashKey);
  }
}
//实例化类
$obj=CartSingleton::getInstance();

希望本文所述对大家PHP程序设计有所帮助。

延伸 · 阅读

精彩推荐