Lock helper


1Presentation

Helper used to lock access to a file. If no file is specified, the running PHP script will be locked.

The object can be called up in two different ways, either by instantiating it conventionally, or by using static methods.
Each solution is used in a different way:

  • Static calls: By default, locking is non-blocking (if the file is already locked, the function returns false immediately). To unlock the file, another static function must be called, again providing the path to the file that was locked.
  • Instantiation: By default, locking is blocking (if the file is already locked, the object waits for it to be released before locking it in turn, then returning the hand). To unlock the file, the object instance must be destroyed.

Files still locked at the end of script execution are automatically unlocked. It is therefore not always necessary to unlock them explicitly.


2Static calls

The simplest way to lock (non-blocking) the execution of a script is to write the following code:

use \Temma\Utils\Lock as TµLock;

if (!TµLock::lock()) {
    // the program is already running
    exit();
}
// rest of the script

To lock a specific file, and unlock it later:

use \Temma\Utils\Lock as TµLock;

TµLock::lock('/chemin/vers/fichier', true);
// ... applicative code
TµLog::unlock('/chemin/vers/fichier');

3Instanciation

To lock access to a file, and unlock it later:

use \Temma\Utils\Lock as TµLock;

// file lock
try {
    $lock = new TµLock('/path/to/file');
} catch (\Temma\Exceptions\IO $eio) {
    // there was an error
}
// ... applicative code
// unlock
unset($lock);

To lock access to a file in a non-blocking way, and unlock it later:

use \Temma\Utils\Lock as TµLock;

// file lock
try {
    $lock = new TµLock('/path/to/file', false);
} catch (\Temma\Exceptions\IO $eio) {
    // there was an error
} catch (\Temma\Exceptions\Application $ea) {
    // the file is already locked
}
// ... applicative code
// unlock
unset($lock);