1 | <?php |
||
19 | class MySqlLock extends LockAbstract |
||
20 | { |
||
21 | /** |
||
22 | * MySql connections |
||
23 | * |
||
24 | * @var PDO[] |
||
25 | */ |
||
26 | protected $pdo = array(); |
||
27 | |||
28 | protected $user; |
||
29 | protected $password; |
||
30 | protected $host; |
||
31 | protected $port; |
||
32 | protected $classname; |
||
33 | |||
34 | /** |
||
35 | * Provide data for PDO connection |
||
36 | * |
||
37 | * @param string $user |
||
38 | * @param string $password |
||
39 | * @param string $host |
||
40 | * @param int $port |
||
41 | * @param string $classname class name to create as PDO connection |
||
42 | */ |
||
43 | public function __construct($user, $password, $host, $port = 3306, $classname = 'PDO') |
||
53 | |||
54 | 5 | public function __clone() |
|
59 | |||
60 | /** |
||
61 | * Acquire lock |
||
62 | * |
||
63 | * @param string $name name of lock |
||
64 | * @param null|int $timeout 1. null if you want blocking lock |
||
65 | * 2. 0 if you want just lock and go |
||
66 | * 3. $timeout > 0 if you want to wait for lock some time (in milliseconds) |
||
67 | * @return bool |
||
68 | */ |
||
69 | 16 | public function acquireLock($name, $timeout = null) |
|
77 | |||
78 | /** |
||
79 | * @param string $name |
||
80 | * @param bool $blocking |
||
81 | * @return bool |
||
82 | */ |
||
83 | 16 | protected function getLock($name, $blocking) |
|
84 | { |
||
85 | 16 | return !$this->isLocked($name) && $this->pdo[$name]->query( |
|
86 | 16 | sprintf( |
|
87 | 16 | 'SELECT GET_LOCK(%s, %d)', |
|
88 | 16 | $this->pdo[$name]->quote($name), |
|
89 | 0 |
||
90 | ), |
||
91 | 16 | PDO::FETCH_COLUMN, |
|
92 | 0 |
||
93 | 16 | )->fetch(); |
|
94 | } |
||
95 | |||
96 | /** |
||
97 | * Release lock |
||
98 | * |
||
99 | * @param string $name name of lock |
||
100 | * @return bool |
||
101 | */ |
||
102 | 16 | public function releaseLock($name) |
|
103 | { |
||
104 | 16 | if (!$this->setupPDO($name)) { |
|
105 | return false; |
||
106 | } |
||
107 | |||
108 | 16 | $released = (bool) $this->pdo[$name]->query( |
|
109 | 16 | sprintf( |
|
110 | 16 | 'SELECT RELEASE_LOCK(%s)', |
|
111 | 16 | $this->pdo[$name]->quote($name) |
|
112 | ), |
||
113 | 16 | PDO::FETCH_COLUMN, |
|
114 | 0 |
||
115 | 16 | )->fetch(); |
|
116 | |||
117 | 16 | if (!$released) { |
|
118 | 2 | return false; |
|
119 | } |
||
120 | |||
121 | 16 | unset($this->pdo[$name]); |
|
122 | 16 | unset($this->locks[$name]); |
|
123 | |||
124 | 16 | return true; |
|
125 | } |
||
126 | |||
127 | /** |
||
128 | * Check if lock is locked |
||
129 | * |
||
130 | * @param string $name name of lock |
||
131 | * @return bool |
||
132 | */ |
||
133 | 16 | public function isLocked($name) |
|
148 | |||
149 | /** |
||
150 | * @param string $name |
||
151 | * @return bool |
||
152 | */ |
||
153 | 16 | protected function setupPDO($name) |
|
164 | |||
165 | 5 | public function __destruct() |
|
166 | { |
||
173 | } |
||
174 |