FileLocker.class.php

Go to the documentation of this file.
00001 <?php
00002 /***************************************************************************
00003  *   Copyright (C) 2006-2008 by Konstantin V. Arkhipov                     *
00004  *                                                                         *
00005  *   This program is free software; you can redistribute it and/or modify  *
00006  *   it under the terms of the GNU Lesser General Public License as        *
00007  *   published by the Free Software Foundation; either version 3 of the    *
00008  *   License, or (at your option) any later version.                       *
00009  *                                                                         *
00010  ***************************************************************************/
00011 
00017     final class FileLocker extends BaseLocker
00018     {
00019         private $directory = null;
00020         
00021         public function __construct($directory = 'file-locking/')
00022         {
00023             $this->directory = ONPHP_TEMP_PATH.$directory;
00024             
00025             if (!is_writable($this->directory)) {
00026                 if (!mkdir($this->directory, 0700, true)) {
00027                     throw new WrongArgumentException(
00028                         "can not write to '{$directory}'"
00029                     );
00030                 }
00031             }
00032         }
00033         
00034         public function get($key)
00035         {
00036             $this->pool[$key] = fopen($this->directory.$key, 'w+');
00037             
00038             return flock($this->pool[$key], LOCK_EX);
00039         }
00040         
00041         public function free($key)
00042         {
00043             return flock($this->pool[$key], LOCK_UN);
00044         }
00045         
00046         public function drop($key)
00047         {
00048             try {
00049                 fclose($this->pool[$key]);
00050                 return unlink($this->directory.$key);
00051             } catch (BaseException $e) {
00052                 unset($this->pool[$key]); // already race-removed
00053                 return false;
00054             }
00055         }
00056     }
00057 ?>