PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php class Lock { /** * Summary of key * @var string */ public $key; /** * Summary of ttl * @var int */ public $ttl = 0; /** * Summary of __construct * @param string $key * @param int $ttl */ public function __construct($key, $ttl = 0) { $this->key = $key; $this->ttl = $ttl; } } interface LockService { /** * Summary of acquire * @param string $key * @param int $ttl * @return Lock|null */ public function acquire($key, $ttl = 0); public function release(Lock $lock); } class MysqlLockService implements LockService { /** * Summary of table_name * @var string */ private $table_name; /** * @var PDO $pdo */ private $pdo; public function __construct($table_name = 'lock_service', PDO $pdo) { $this->table_name = $table_name; $this->pdo = $pdo; $this->init(); } private function init() { $this->pdo->exec("CREATE TABLE IF NOT EXISTS `{$this->table_name}` (`id` char(128) unique, `ttl` int(11) unsigned) engine innodb default character set utf8"); } private function cleanup() { $stmt = $this->pdo->prepare("DELETE FROM `{$this->table_name}` WHERE ttl < ?"); $stmt->execute(array(time())); } /** * Summary of acquire * @param string $key * @param int $ttl * @return Lock|null */ public function acquire($key, $ttl = 300) { try { $this->cleanup(); $id = hash('sha512', $key); $stmt = $this->pdo->exec("INSERT INTO `{$this->table_name}` (`id`, `ttl`) VALUES (?, ?)"); $stmt->execute(array($id, time() + $ttl)); return new Lock($key, $ttl); } catch (\Exception $th) { return null; } } /** * @param Lock $lock * @return mixed */ public function release(Lock $lock) { $id = hash('sha512', $lock->key); $stmt = $this->pdo->exec("DELETE FROM `{$this->table_name}` WHERE `id` = ?"); $stmt->execute(array($id)); $this->cleanup(); } } $lock_service = new MysqlLockService('lock_table', $pdo); $lock = $lock_service->acquire("teste"); var_dump($lock);
Show:  
Copy Clear