* @package WB * @subpackage Lock */ /** * Simple Locking * * @todo use drivers instead of actual implementing file lock in this class * @version 0.1.0 * @package WB * @subpackage Lock */ class WBLock extends WBStdClass { const SHARED = 1; const EXCLUSIVE = 2; private $name = ''; private $block = false; private $path = '%s/var/lock/%s.lock'; private $hdl = null; /** * Constructor */ final public function __construct($parameter = array()) { if (!empty($parameter['name'])) { $this->setName($parameter['name']); } } /** * Destructor */ final public function __destruct() { if (empty($this->hdl)) { return; } fclose($this->hdl); } /** * Switch Blocking * * Set locking mode to blocking or non blocking * @param bool true for blocking */ public function useBlocking($use = true) { $this->block = $use; } /** * Set Lock Name * * @param string name for lock */ public function setName($name) { if (!empty($this->hdl)) { fclose($this->hdl); } $this->name = $name; $file = sprintf($this->path, WBParam::get('wb/dir/base'), $this->name); if (!file_exists($file)) { touch($file); chmod($file, 0666); } $this->hdl = fopen($file, 'w'); } /** * Aquire Lock * * @param int EXCLUSIVE|SHARED */ public function acquire($type = self::EXCLUSIVE) { $mode = 0; if (!$this->block) { $mode |= LOCK_NB; } switch ($type) { case self::EXCLUSIVE: $mode |= LOCK_EX; break; case self::SHARED: $mode |= LOCK_SH; break; } return flock($this->hdl, $mode); } /** * Release Lock */ public function release() { flock($this->hdl, LOCK_UN); } }