-
Notifications
You must be signed in to change notification settings - Fork 9
/
UnitOfWork.php
92 lines (75 loc) · 1.73 KB
/
UnitOfWork.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
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
85
86
87
88
89
90
91
92
<?php
class UnitOfWork extends CComponent
{
public $name;
private $_items = array();
private $_insertItems = array();
private $_updateItems = array();
private $_deleteItems = array();
private $_dbconns = array();
/**
* 注册一个实体
* @param CEntity $entity
*/
public function register($entity)
{
$cacheKey = $entity->getCackeKey();
$item[$cacheKey] = $entity;
$entity->getDbConnection()->beginTransaction();
}
public function commit()
{
foreach($this->_items as $key => $entity)
{
if($entity->getIsRemoveRecord())
{
$this->_deleteItems[] = $entity;
}
else if($entity->isDirty())
{
if($entity->getIsNewRecord()) {
$this->_insertItems[] = $entity;
} else {
$this->_updateItems[] = $entity;
}
}
$entity->setDbWrite();
$db = $entity->getDbConnection();
$this->dbconns["{$db->connectionString}-{$db->username}"] = $db;
}
foreach($this->_dbconns as $conn)
{
$entity->getDbConnection()->beginTransaction();
}
try {
foreach ($this->_updateItems as $key => $entity) {
if($entity->update())
throw new CDbException('并发冲突');
}
foreach ($this->_insertItems as $key => $entity) {
$entity->save(false);
}
foreach ($this->_deleteItems as $key => $entity) {
$entity->delete();
}
foreach($this->_dbconns as $conn)
{
$entity->getDbConnection()->commit();
}
} catch (Exception $e) {
foreach($this->_dbconns as $conn)
{
$entity->getDbConnection()->rollback();
}
throw $e;
}
}
public function rest()
{
$this->updateItems = array();
$this->insertItems = array();
$this->deleteItems = array();
$this->items = array();
$this->dbconns = array();
}
}