PHP code example of zaber-dev / laravel-lock

1. Go to this page and download the library: Download zaber-dev/laravel-lock library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zaber-dev / laravel-lock example snippets


// Option 1: High-level atomic block execution (acquires lock + executes + auto-releases in finally)
Lock::for('billing_charge', $user)
    ->block(function () {
        // Critical section...
    });

// Option 2: Step-by-step acquisition and release with automatic owner detection
if (Lock::for('billing_charge', $user)
        ->ttl(60)
        ->acquire()) {
    try {
        // Do work...
    } finally {
        Lock::for('billing_charge', $user)->release();
    }
}

return [
    /*
    |--------------------------------------------------------------------------
    | Default Lock Driver
    |--------------------------------------------------------------------------
    |
    | Supported drivers: "cache", "database"
    |
    */
    'default' => env('LOCK_DRIVER', 'cache'),

    'drivers' => [
        'cache' => [
            'driver' => 'cache',
            'store' => env('LOCK_CACHE_STORE', null),
            'prefix' => 'locks:',
        ],
        'database' => [
            'driver' => 'database',
            'table' => 'locks',
        ],
    ],

    'events' => [
        'dispatch' => true,
    ],
];

use ZaberDev\Lock\Facades\Lock;

$builder = Lock::for('billing_charge', $user)
    ->ttl(60)
    ->owner('worker_abc'); // Optional: explicit override (defaults to automatic owner detection)

if ($builder->acquire()) {
    try {
        // Lock acquired, execute sensitive logic...
    } finally {
        $builder->release();
    }
} else {
    // Lock is currently held by someone else
}

// Check lock status
$isLocked = Lock::for('billing_charge', $user)->isLocked();
$info = Lock::for('billing_charge', $user)->info(); // LockInfo DTO

Lock::for('billing_charge', $user)->block(function () use ($stripeService, $user) {
    $stripeService->charge($user);
});

Lock::for('billing_charge', $user)->forceRelease();

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use ZaberDev\Lock\HasLocks;

class User extends Authenticatable
{
    use HasLocks;
}

$user = User::find(1);

// Acquire a 60-second lock on "billing_charge" for this user
if ($user->lock('billing_charge')->ttl(60)->acquire()) {
    try {
        // Charge user...
    } finally {
        $user->lock('billing_charge')->release();
    }
}

// Check status
if ($user->lock('billing_charge')->isLocked()) {
    return response()->json(['message' => 'Action locked.'], 429);
}

// Get all database lock records assigned to this user
$activeLocks = $user->locks()->where('expires_at', '>', now())->get();

// Delete all lock records for this user
$user->locks()->delete();

use Illuminate\Support\Facades\Route;

// Enforce a 30-second lock on billing endpoints per User / IP address
Route::post('/billing/charge', [BillingController::class, 'charge'])
    ->middleware('lock:billing_charge,30');

// Use a specific storage engine
Route::post('/api/payout', [PayoutController::class, 'store'])
    ->middleware('lock:payout,60,database');

// Store transient mutex checks in fast cache/Redis
Lock::for('api_sync', $ip)->using('cache')->ttl(15)->acquire();

// Store critical transaction locks inside persistent database tables
Lock::for('account_transfer', $user)->using('database')->ttl(120)->acquire();

use ZaberDev\Lock\Contracts\LockDriverContract;
use ZaberDev\Lock\Facades\Lock;

public function boot(): void
{
    Lock::extend('redis-cluster', function ($app) {
        return new MyRedisClusterLockDriver($app['redis']);
    });
}

use Illuminate\Support\Facades\Schedule;
use ZaberDev\Lock\Models\LockModel;

Schedule::command('model:prune', ['--model' => LockModel::class])->daily();
bash
php artisan vendor:publish --provider="ZaberDev\Lock\LockServiceProvider"
bash
php artisan migrate