FileLocker.class.php

Go to the documentation of this file.
00001 <?php
00002 /***************************************************************************
00003  *   Copyright (C) 2006-2007 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 /* $Id: FileLocker.class.php 4687 2007-12-09 18:57:18Z voxus $ */
00012 
00018     final class FileLocker extends BaseLocker
00019     {
00020         private $directory = null;
00021         
00022         public function __construct($directory = 'file-locking/')
00023         {
00024             $this->directory = ONPHP_TEMP_PATH.$directory;
00025             
00026             if (!is_writable($this->directory)) {
00027                 if (!mkdir($this->directory, 0700, true)) {
00028                     throw new WrongArgumentException(
00029                         "can not write to '{$directory}'"
00030                     );
00031                 }
00032             }
00033         }
00034         
00035         public function get($key)
00036         {
00037             $this->pool[$key] = fopen($this->directory.$key, 'w+');
00038             
00039             $mseconds = 0;
00040             
00041             while (!flock($this->pool[$key], LOCK_EX)) {
00042                 usleep(200);
00043                 
00044                 // give up on ten seconds timeout
00045                 if (($mseconds += 200) > 10000) {
00046                     return false;
00047                 }
00048             }
00049             
00050             return true;
00051         }
00052         
00053         public function free($key)
00054         {
00055             return flock($this->pool[$key], LOCK_UN);
00056         }
00057         
00058         public function drop($key)
00059         {
00060             try {
00061                 return fclose($this->pool[$key]);
00062             } catch (BaseException $e) {
00063                 unset($this->pool[$key]); // already race-removed
00064                 return false;
00065             }
00066         }
00067     }
00068 ?>

Generated on Sun Dec 9 21:56:23 2007 for onPHP by  doxygen 1.5.4