PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
create table if not exists lock_service (`id` char(128) unique, `ttl` int(11) unsigned) engine innodb default character set utf8; insert into lock_service (id, ttl) values ('teste', 300); select * from lock_service;
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(PDO $pdo, $table_name = 'lock_service') { $this->table_name = $table_name; $this->pdo = $pdo; $this->init(); } private function init() { $this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $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->prepare("INSERT INTO `{$this->table_name}` (`id`, `ttl`) VALUES (?, ?)"); $stmt->execute(array($id, time() + $ttl)); return new Lock($key, $ttl); } catch (\Exception $th) { var_dump($th); return null; } } /** * @param Lock $lock * @return mixed */ public function release(Lock $lock) { $id = hash('sha512', $lock->key); $stmt = $this->pdo->prepare("DELETE FROM `{$this->table_name}` WHERE `id` = ?"); $stmt->execute(array($id)); $this->cleanup(); } } try { $lock_service = new MysqlLockService($pdo); $lock = $lock_service->acquire("teste"); var_dump($lock); } catch (\Exception $e) { var_dump($e); }
Show:  
Copy Clear