-
Notifications
You must be signed in to change notification settings - Fork 9
/
DbIDGenerator.php
59 lines (49 loc) · 1.48 KB
/
DbIDGenerator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
/**
* This is the model class for table "idgenerator".
*
* The followings are the available columns in table 'idgenerator':
* @property string $nextid
*/
class DbIDGenerator
{
const QUEUE_SIZE = 10;
const END_OF_QUEUE = self::QUEUE_SIZE;
private $offset;
private $queue;
static private $idgenerator;
private function __construct()
{
$this->queue = array_fill(0, self::QUEUE_SIZE, 0);
$this->offset = self::END_OF_QUEUE;
}
public function getNextID()
{
if ($this->offset == self::END_OF_QUEUE)
{
$this->fillQueueFromDb();
$this->offset = 0;
}
return $this->queue[$this->offset++];
}
private function fillQueueFromDb()
{
$queueSize = self::QUEUE_SIZE;
$sql = "update idgenerator set nextid=LAST_INSERT_ID(nextid+$queueSize)";
Yii::app()->db->createCommand($sql)->execute();
$dataReader = Yii::app()->db->createCommand("select LAST_INSERT_ID() as nextid")->query();
$dataReader->bindColumn(1, $nextId);
if($dataReader->read() !== false) {
$i = self::END_OF_QUEUE;
while ($i > 0)
{
$this->queue[--$i] = --$nextId;
}
}
}
public static function nextId() {
if(DbIDGenerator::$idgenerator == null)
DbIDGenerator::$idgenerator = new DbIDGenerator;
return DbIDGenerator::$idgenerator->getNextID();
}
}