arnapou/lock

Library - Simple lock interface and adapters.

v1.1 2024-02-03 19:46 UTC

This package is auto-updated.

Last update: 2024-02-03 18:47:57 UTC


README

pipeline coverage

This library helps you to manage basic locks for async processes or race condition problems.

Installation

composer require arnapou/lock

packagist 👉️ arnapou/lock

Introduction

This library provides basic lock interfaces and adapters.

It mainly follows the KISS principle.

If you need advanced features, go look at symfony/lock or other equivalent libraries.

Here, the goal is minimalist code for 90% of needs.

Basic usage

$locker = new \Arnapou\Lock\Adapter\RedisLocker(
    redis: $redis,
    autorelease: true,
    defaultTtl: 60,
    namespace: 'project:locks:'  
);

if ($locker->acquire('my_lock')) {
    // do your process
    $locker->release('my_lock');
} else {
    // delay or report an error
}

Decorators

We can enhance the behaviour for instance with a retry mechanism :

$waitingLocker = new \Arnapou\Lock\Decorator\WaitingLocker(
    internal: $redisLocker,
    maxTotalWaitSeconds: 1.0,
    minLoopWaitMilliseconds: 20,
    maxLoopWaitMilliseconds: 150
);

if ($locker->acquire('my_lock')) {
    // do your process
    $locker->release('my_lock');
} else {
    // delay or report an error
}

Changelog versions

StartTag, BranchPhp
09/01/20241.x, main8.3