redisを使用してカート機能を実現
3045 ワード
redis = new Redis;
$this->redis->connect('127.0.0.1', 6379);
}
public function addToCart($gid, $cartNum=1)
{
session_start();
if ($gid <= 0) {
throw new Exception(" ID");
}
// ID
$goodData = $this->goodsData($gid);
$key = 'cart:'.session_id().':'.$gid;//id :1、 2、
// $data = $this->redis->hget($key, 'id');
$data = $this->redis->exists($key);
// ,
if (!$data) {
//
//
$goodData['num'] = $cartNum;
// redis hash
$this->redis->hmset($key, $goodData);
$key1 = 'cart:ids:set:'.session_id();
// ID ,
$this->redis->sadd($key1, $gid);
} else {
// ,
$originNum = $this->redis->hget($key, 'num');
//
$newNum = $originNum + $cartNum;
$this->redis->hset($key, 'num', $newNum);
}
}
//
public function showCartList()
{
session_start();
$sessId = session_id();
$key = 'cart:ids:set:'.session_id();
// ID
$idArr = $this->redis->sMembers($key);
for ($i=0; $i';
$list[] = $this->redis->hGetAll($k);
}
var_dump($list);
}
public function goodsData($gid)
{
$goodsData = array(
1 => array(
'id' => 1,
'gname' => 'xxoo',
'price' => '1.5'
),
2 => array(
'id' => 2,
'gname' => 'xxoo22',
'price' => '221.5'
),
3 => array(
'id' => 3,
'gname' => 'xxoo33',
'price' => '331.5'
),
4 => array(
'id' => 4,
'gname' => 'xxoo44',
'price' => '4441.5'
),
);
return $goodsData[$gid];
}
}
$ceshi = new Cart();
$ceshi->addToCart(2,2);
echo session_id();