Skip to content

Instantly share code, notes, and snippets.

@garoevans
Last active August 29, 2015 14:03
Show Gist options
  • Save garoevans/ef4dd891ce3f9783f866 to your computer and use it in GitHub Desktop.
Save garoevans/ef4dd891ce3f9783f866 to your computer and use it in GitHub Desktop.
<?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