主頁 > 知識庫 > PHP+redis實現(xiàn)的購物車單例類示例

PHP+redis實現(xiàn)的購物車單例類示例

熱門標簽:團購網(wǎng)站 Linux服務器 電子圍欄 Mysql連接數(shù)設置 科大訊飛語音識別系統(tǒng) 阿里云 服務器配置 銀行業(yè)務

本文實例講述了PHP+redis實現(xiàn)的購物車單例類。分享給大家供大家參考,具體如下:

?php
/**
 * 購物車單例類
 *
 * @author YING
 * @param void
 * @return void
 */
class CartSingleton
{
  //定義一個靜態(tài)的私有變量
  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()
  {
  }
  //公有的靜態(tài)方法
  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鍵名
    //查詢數(shù)據(jù)
    return $this->redis->hGetAll($hashKey);
  }
}
//實例化類
$obj=CartSingleton::getInstance();

更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php+redis數(shù)據(jù)庫程序設計技巧總結》、《php面向對象程序設計入門教程》、《PHP基本語法入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》

希望本文所述對大家PHP程序設計有所幫助。

您可能感興趣的文章:
  • Redis實戰(zhàn)之商城購物車功能的實現(xiàn)代碼

標簽:江蘇 大理 萍鄉(xiāng) 廣元 棗莊 蚌埠 衡水 衢州

巨人網(wǎng)絡通訊聲明:本文標題《PHP+redis實現(xiàn)的購物車單例類示例》,本文關鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266