php内置的spl, 有许多默认的接口, 但是在平常写业务逻辑代码用到的不多。就在今天想迭代器(Iterator)的应用场景时, 突然发现一个很好用的场景, 重复的从数据库中批量获取数据, 代码如下。

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/*
* 查询迭代器
* 韩晓林
* 2017年06月28日11:35:38
* */
Class tradeQueryIterator implements Iterator{
private $id = 0;
private $maxId = 0;
private $redis = null;
private $redisKey = null;
private $data = [];
private $queryMaxId;
private $queryData;
private $transaction = null;

public function __construct(callable $queryMaxId,callable $queryData, $redisKey = null)
{
$this->redis = sfContext::getInstance()->getDatabaseConnection('zhuangbeiRedis');
$this->redis->select(6);

if($redisKey){
$this->redisKey = $redisKey ;
}else{
$trace = debug_backtrace();
$this->redisKey = 'trade2017task:Iterator:tmp:key'.$trace[0]['function'].$trace[1]['function'];
}

$this->queryMaxId = $queryMaxId;
$this->queryData = $queryData;
}

public function rewind()
{
$this->id = (int)$this->redis->get($this->redisKey);
$this->maxId = call_user_func($this->queryMaxId);
}

public function current()
{
//执行事务
if($this->transaction != null){
$this->redis->EXEC();
}
//开始事务
$this->redis->MULTI();

//数据源
$this->data = call_user_func($this->queryData, $this->id);

if(count($this->data) > 0){
$this->id = $this->data[count($this->data)-1]->id;

$this->redis->set($this->redisKey, $this->id);

$this->transaction = 1;
}

return $this->data;
}

public function next()
{
}

public function key()
{
return $this->id;
}

public function valid()
{
$isValid = $this->id != $this->maxId;
if(!$isValid){
$this->redis->del($this->redisKey);
if($this->transaction != null){
$this->redis->EXEC();
}
}
return $isValid;
}
}


有了这个查询的迭代器之后就会很方便的从数据库获取到所有数据了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$task = new tradeQueryIterator(function (){
$supplier = trdxxxTable::getInstance()->createQuery()->select('max(id) max_id')->andwhere('name = ?', '其他')->fetchOne();
if($supplier){
return $supplier->max_id;
}else{
return 0;
}
},function ($id){
return trdxxxTable::getInstance()->createQuery()->andwhere('id > ?', $id)->andwhere('name = ?', '其他')->limit(2)->execute();
});

foreach ($task as $data){
foreach ($data as $val) {
echo $val->id."\n";
}
}
exit;