PHP code example of brick / lock

1. Go to this page and download the library: Download brick/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/ */

    

brick / lock example snippets


use Brick\Lock\Database\Connection\PdoConnection;
use Brick\Lock\Driver\MysqlLockDriver;

$pdo = new PDO('mysql:host=localhost', 'user', 'password');
$connection = new PdoConnection($pdo);
$driver = new MysqlLockDriver($connection);

use Brick\Lock\LockFactory;

$lockFactory = new LockFactory($driver);

$lock = $lockFactory->createLock('my_lock_name');

$lock->acquire();
// ... do some work while the lock is held ...
$lock->release();

    $lock->acquire();
    

    if ($lock->tryAcquire()) {
        // the lock is acquired
    } else {
        // the lock is currently held by another process
    }
    

    if ($lock->tryAcquireWithTimeout(10)) {
        // the lock is acquired
    } else {
        // the lock could not be acquired after 10s
    }
    

    $lock->release();
    

    $lock->wait();
    

    if ($lock->tryWaitWithTimeout(10)) {
        // the lock was available before the end of the timeout
    } else {
        // the lock was still not available after 10s
    }
    

    $result = $lock->synchronize(function() {
        // ...do some work that '
    

    $result = $lock->trySynchronize(function() {
        // ...do some work that    // the lock was acquired and the closure was executed
        // $result->returnValue === 'some value'
    } else {
        // the lock was not available
    }
    

    $result = $lock->trySynchronizeWithTimeout(10, function() {
        // ...do some work that was acquired and the closure was executed
        // $result->returnValue === 'some value'
    } else {
        // the lock was still not available after 10s
    }
    

$lock = $lockFactory->createMultiLock(['my_lock_name_1', 'my_lock_name_2']);

$lock->acquire(); // Counter: 1 - blocks until the lock is available
$lock->acquire(); // Counter: 2 - returns immediately
$lock->acquire(); // Counter: 3 - returns immediately

$lock->release(); // Counter: 2 - lock is still held
$lock->release(); // Counter: 1 - lock is still held  
$lock->release(); // Counter: 0 - lock is now fully released