Skip to content

Instantly share code, notes, and snippets.

@crossai-2033
Created April 10, 2015 07:20
Show Gist options
  • Save crossai-2033/c41412df1d985afe4652 to your computer and use it in GitHub Desktop.
Save crossai-2033/c41412df1d985afe4652 to your computer and use it in GitHub Desktop.
用来替代数据库自增id的gen设计
<?php
class IdGen {/*{{{*/
private $executor = null;
public function __construct($executor) {/*{{{*/
$this->executor = $executor;
}/*}}}*/
public function genId($key) {/*{{{*/
$sql = 'update id_gen set max_id = last_insert_id(max_id + 1) ';
$sql .= 'where keyword = ?';
$this->executor->exeNoQuery($sql, array($key));
$sql = 'select last_insert_id() as max_id';
$row = $this->executor->query($sql);
return $row['max_id'];
}/*}}}*/
}/*}}}*/
protected function _genId() {/*{{{*/
$cls = get_class($this);
$cls = strtolower($cls);
return LoaderSvc::loadIdGen()->genId($cls);
}/*}}}*/
protected function _fillPublicCols() {/*{{{*/
$now = $this->_getNow();
$this->id = $this->_genId();
$this->ctime = $now;
}/*}}}*/
-- Adminer 3.7.0 MySQL dump
SET NAMES utf8;
SET foreign_key_checks = 0;
SET time_zone = '+08:00';
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
DROP TABLE IF EXISTS `id_gen`;
CREATE TABLE `id_gen` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`keyword` varchar(32) NOT NULL DEFAULT '',
`max_id` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `keyword` (`keyword`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 2015-04-10 15:17:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment