PHP code example of malkusch / lock

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

    

malkusch / lock example snippets


$newBalance = $mutex->synchronized(static function () use ($bankAccount, $amount) {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    if ($balance < 0) {
        throw new \DomainException('You have no credit');
    }
    $bankAccount->setBalance($balance);

    return $balance;
});

$newBalance = $mutex->check(static function () use ($bankAccount, $amount): bool {
    return $bankAccount->getBalance() >= $amount;
})->then(static function () use ($bankAccount, $amount) {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    $bankAccount->setBalance($balance);

    return $balance;
});

try {
    $result = $mutex->synchronized(static function () {
        if (someCondition()) {
            throw new \DomainException();
        }

        return 'result';
    });
} catch (LockReleaseException $e) {
    if ($e->getCodeException() !== null) {
        // do something with the $e->getCodeException() exception
    } else {
        // do something with the $e->getCodeResult() result
    }

    throw $e;
}

$mutex = new FlockMutex(fopen(__FILE__, 'r'));

$memcached = new \Memcached();
$memcached->addServer('localhost', 11211);

$mutex = new MemcachedMutex('balance', $memcached);

$redis = new \Redis();
$redis->connect('localhost');
// OR $redis = new \Predis\Client('redis://localhost');

$mutex = new RedisMutex($redis, 'balance');

$semaphore = sem_get(ftok(__FILE__, 'a'));
$mutex = new SemaphoreMutex($semaphore);

$pdo = new \PDO('mysql:host=localhost;dbname=test', 'username');
$mutex = new MySQLMutex($pdo, 'balance', 15);

$pdo = new \PDO('pgsql:host=localhost;dbname=test', 'username');
$mutex = new PostgreSQLMutex($pdo, 'balance');

$mutex = new DistributedMutex([
    new \Predis\Client('redis://10.0.0.1'),
    new \Predis\Client('redis://10.0.0.2'),
], 'balance');