<?php
/**
* 基于Redis的全局订单号id
*
* @author chendahui
**/
namespace sitelibrary;
class OrdersNum {
private $_r;
private $_host;
private $_port;
private $_passwd;
private $_prefix;
private $_len;
function __construct() {
try {
$redisconfig = array(
'host' => REDIS_HOST,
'port' => REDIS_PORT,
'password' => REDIS_PASSWORD,
'prefix' => 'CB',
'len' => 3,
);
$this->setBuilder($redisconfig);
$this->_r = new Redis();
$ret = $this->_r->connect($this->_host, $this->_port);
if (!$ret) {
die("[redis connect error]");
}
$this->_r->auth($this->_passwd);
}
catch (Exception $e) {
trace($e->getMessage());
}
}
private function setBuilder($redisconfig) {
$this->_host = $redisconfig['host'];
$this->_port = $redisconfig['port'];
$this->_passwd = $redisconfig['password'];
$this->_prefix = $redisconfig['prefix'];
$this->_len = $redisconfig['len'];
}
/**
* 生成当天全局唯一自增id
*
* @param integer $key
*
* @return $id
* @author chendahui
**/
private function nextId($key) {
$id = $this->_r->incr($this->_prefix.":".$key);
$l = strlen($id);
if ($l>$this->_len) {
return $id;
} else {
return str_repeat(0, $this->_len-$l).$id;
}
}
/**
* 获取订单号
*
* @return integer
* @author chendahui
**/
public function getOrdersNum() {
$key = date('Ymd', time());
return $this->_prefix.$key.$this->nextId($key);
}
}