PHPackages                             mvonline/locker - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. mvonline/locker

ActiveLibrary[Caching](/categories/caching)

mvonline/locker
===============

A comprehensive, cache-driver-agnostic distributed locking framework for Laravel

1.0.0(4mo ago)121MITPHPPHP ^8.1CI failing

Since Dec 26Pushed 4mo agoCompare

[ Source](https://github.com/mvonline/locker)[ Packagist](https://packagist.org/packages/mvonline/locker)[ RSS](/packages/mvonline-locker/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (7)Versions (2)Used By (0)

Locker - Distributed Locking Framework for Laravel
==================================================

[](#locker---distributed-locking-framework-for-laravel)

A comprehensive, cache-driver-agnostic distributed locking framework for Laravel that extends Laravel's cache abstraction while remaining compatible with all native cache drivers.

Features
--------

[](#features)

- **12 Lock Types**: Simple, Safe, Redlock, Reentrant, Read-Write, Semaphore, Fair, Fencing Token, Striped, Multi-Resource, Watchdog, and Leased locks
- **Cache Driver Agnostic**: Works with Redis, Database, File, Memcached, and Array cache drivers
- **Fluent API**: Chainable, intuitive interface
- **Event System**: Comprehensive event dispatching for lock lifecycle
- **Automatic Release**: Locks are automatically released after callback execution
- **Blocking &amp; Non-blocking**: Configurable retry logic with exponential backoff
- **Fully Tested**: Comprehensive test suite targeting 100% coverage

Installation
------------

[](#installation)

```
composer require mvonline/locker
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag=locker-config
```

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use Mvonline\Locker\Facades\Locker;

// Simple lock with callback
Locker::lock('user-update-123')
    ->type('simple')
    ->ttl(10)
    ->run(fn () => User::find(123)->update($data));

// Blocking lock
Locker::lock('payment-process')
    ->type('safe')
    ->ttl(30)
    ->block(5)
    ->run(fn () => processPayment());
```

### Quick Helpers

[](#quick-helpers)

```
// Simple lock
Locker::simple('key', fn() => { /* work */ });

// Safe lock
Locker::safe('key', fn() => { /* work */ });

// Reentrant lock
Locker::reentrant('key', fn() => { /* work */ });

// Semaphore (5 concurrent)
Locker::semaphore('key', 5, fn() => { /* work */ });

// Read lock
Locker::read('key', fn() => { /* read */ });

// Write lock
Locker::write('key', fn() => { /* write */ });
```

### Using the HasLocks Trait

[](#using-the-haslocks-trait)

```
use Mvonline\Locker\Traits\HasLocks;

class OrderProcessor
{
    use HasLocks;

    public function processOrder()
    {
        $this->lockResource('order-'.$this->id)
             ->type('reentrant')
             ->ttl(30)
             ->run(fn() => {
                 // critical section
             });
    }

    // Or use the simpler helper
    public function updateOrder()
    {
        $this->withLock('order-'.$this->id, fn() => {
            // protected code
        }, type: 'reentrant', ttl: 60);
    }
}
```

Lock Types
----------

[](#lock-types)

### 1. Simple Lock

[](#1-simple-lock)

Basic atomic lock with no ownership validation.

```
Locker::lock('resource')->type('simple')->ttl(10)->run(fn() => {});
```

### 2. Safe Lock

[](#2-safe-lock)

Lock with unique owner token to prevent accidental unlock.

```
Locker::lock('resource')
    ->type('safe')
    ->owner(auth()->id())
    ->ttl(30)
    ->run(fn() => {});
```

### 3. Redlock (Redis-only)

[](#3-redlock-redis-only)

Distributed lock using Redis Redlock algorithm with quorum.

```
Locker::lock('resource')
    ->type('redlock')
    ->ttl(60)
    ->run(fn() => {});
```

### 4. Reentrant Lock

[](#4-reentrant-lock)

Same owner can re-acquire the lock multiple times.

```
Locker::lock('resource')
    ->type('reentrant')
    ->owner(auth()->id())
    ->ttl(30)
    ->run(fn() => {
        // Can acquire same lock again inside
        Locker::lock('resource')
            ->type('reentrant')
            ->owner(auth()->id())
            ->run(fn() => {});
    });
```

### 5. Read-Write Lock

[](#5-read-write-lock)

Multiple readers or exclusive writer.

```
// Multiple readers allowed
Locker::read('config', fn() => readConfig());

// Exclusive writer
Locker::write('config', fn() => updateConfig($data));
```

### 6. Semaphore Lock

[](#6-semaphore-lock)

Allows N concurrent holders.

```
Locker::lock('api-calls')
    ->type('semaphore')
    ->permits(10)
    ->acquire(1)
    ->block(2)
    ->run(fn() => callExternalApi());
```

### 7. Fair Lock

[](#7-fair-lock)

FIFO ordering prevents starvation.

```
Locker::lock('resource')
    ->type('fair')
    ->ttl(30)
    ->run(fn() => {});
```

### 8. Fencing Token Lock

[](#8-fencing-token-lock)

Monotonic token per acquisition prevents split-brain writes.

```
Locker::lock('resource')
    ->type('fencing')
    ->ttl(30)
    ->run(function($token) {
        // Use $token for ordering operations
    });
```

### 9. Striped Lock

[](#9-striped-lock)

Hash-based sharding reduces contention.

```
Locker::lock('resource')
    ->type('striped')
    ->shardCount(16)
    ->ttl(30)
    ->run(fn() => {});
```

### 10. Multi-Resource Lock

[](#10-multi-resource-lock)

Atomic multi-lock acquisition with deadlock prevention.

```
Locker::lock(['account-1', 'account-2'])
    ->type('multi')
    ->ttl(30)
    ->run(fn() => transferMoney());
```

### 11. Watchdog Lock

[](#11-watchdog-lock)

Auto-renewal of TTL before expiration.

```
Locker::lock('video-processing')
    ->type('watchdog')
    ->ttl(60)
    ->renewEvery(15)
    ->run(fn() => processLargeVideo());
```

### 12. Leased Lock

[](#12-leased-lock)

Hard TTL expiration with explicit renewal required.

```
$lock = Locker::lock('resource')
    ->type('leased')
    ->ttl(30)
    ->acquire();

try {
    doWork();
    $lock->renew(); // Extend lease
} finally {
    $lock->release();
}
```

Manual Lock Control
-------------------

[](#manual-lock-control)

```
$lock = Locker::lock('resource')
    ->type('safe')
    ->ttl(30)
    ->acquire();

try {
    // Do work
} finally {
    $lock->release();
}
```

Blocking with Retry
-------------------

[](#blocking-with-retry)

```
Locker::lock('resource')
    ->type('safe')
    ->ttl(30)
    ->block(5) // Wait up to 5 seconds
    ->run(fn() => {});
```

Events
------

[](#events)

The package dispatches events for lock lifecycle:

- `LockAcquired`: When a lock is successfully acquired
- `LockReleased`: When a lock is released
- `LockFailed`: When lock acquisition fails
- `LockTimeout`: When lock acquisition times out
- `LockExtended`: When a lock's TTL is extended

Listen to events:

```
use Mvonline\Locker\Events\LockAcquired;

Event::listen(LockAcquired::class, function ($event) {
    Log::info("Lock acquired: {$event->key} by {$event->owner}");
});
```

Status &amp; Admin
------------------

[](#status--admin)

```
// Check if locked
Locker::isLocked('key');
Locker::isLocked('key', 'simple');

// Force release (use with caution)
Locker::forceRelease('key');
```

Exceptions
----------

[](#exceptions)

The package throws custom exceptions:

- `LockAcquisitionException`: When lock acquisition fails
- `LockReleaseException`: When lock release fails
- `LockTimeoutException`: When lock acquisition times out
- `UnsupportedDriverException`: When lock type is not supported by driver
- `LockOwnershipException`: When lock ownership validation fails

Cache Drivers
-------------

[](#cache-drivers)

The package works with all Laravel cache drivers:

- **Redis**: Full support for all lock types including Redlock
- **Database**: Full support for all lock types
- **File**: Full support for all lock types
- **Memcached**: Full support for all lock types
- **Array**: Full support (for testing only)

Testing
-------

[](#testing)

```
composer test
```

Requirements
------------

[](#requirements)

- PHP 8.1+
- Laravel 10+, 11+, or 12+

License
-------

[](#license)

MIT

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance74

Regular maintenance activity

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

143d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c6011fc855d32ecb6ea1f1f762b6ba10f2bdf763f3784881e921488e6d669a6a?d=identicon)[mvonline](/maintainers/mvonline)

---

Top Contributors

[![mvonline](https://avatars.githubusercontent.com/u/1967927?v=4)](https://github.com/mvonline "mvonline (2 commits)")

---

Tags

concurrencylaravelcachelockdistributed

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mvonline-locker/health.svg)

```
[![Health](https://phpackages.com/badges/mvonline-locker/health.svg)](https://phpackages.com/packages/mvonline-locker)
```

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[laravel-zero/framework

The Laravel Zero Framework.

3371.4M369](/packages/laravel-zero-framework)[dragon-code/laravel-cache

An improved interface for working with cache

6844.8k10](/packages/dragon-code-laravel-cache)[anahkiasen/flatten

A package for the Illuminate framework that flattens pages to plain HTML

33313.0k](/packages/anahkiasen-flatten)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
