Last active
August 29, 2015 14:03
-
-
Save garoevans/ef4dd891ce3f9783f866 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author: gareth | |
*/ | |
class Lock | |
{ | |
/** | |
* @var string | |
*/ | |
private $name; | |
/** | |
* @var string | |
*/ | |
private $directory; | |
/** | |
* @var bool | |
*/ | |
private $hasLock = false; | |
/** | |
* @var Resource | |
*/ | |
private $fp; | |
/** | |
* @param $name | |
* @param string $directory | |
*/ | |
public function __construct($name, $directory = '/tmp') | |
{ | |
$this->name = $name; | |
$this->directory = rtrim($directory, '/'); | |
} | |
/** | |
* @return $this | |
*/ | |
public function getLock() | |
{ | |
$this->fp = fopen(sprintf("%s/%s.lock", $this->directory, $this->name), "w+"); | |
$this->hasLock = flock($this->fp, LOCK_EX | LOCK_NB); | |
return $this; | |
} | |
/** | |
* @return bool | |
*/ | |
public function hasLock() | |
{ | |
return $this->hasLock; | |
} | |
/** | |
* Returns null if there is no lock to release, otherwise returns bool to show success. | |
* | |
* @return bool|null | |
*/ | |
public function releaseLock() | |
{ | |
$res = null; | |
if ($this->hasLock()) { | |
$res = flock($this->fp, LOCK_UN); | |
fclose($this->fp); | |
} | |
return $res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment