PHP code example of pudongping / wise-locksmith

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

    

pudongping / wise-locksmith example snippets




udongping\WiseLocksmith\Locker;

$redisHosts = [
    [
        'host' => '127.0.0.1',
        'port' => 6379
    ],
    [
        'host' => '127.0.0.1',
        'port' => 6380
    ],
    [
        'host' => '127.0.0.1',
        'port' => 6381
    ],
    [
        'host' => '127.0.0.1',
        'port' => 6382
    ],
    [
        'host' => '127.0.0.1',
        'port' => 6383
    ],
];

// Initialize Redis instances if distributed locks or Redlock are needed; otherwise, you can skip this step
$redisInstances = array_map(function ($v) {
    $redis = new \Redis();
    $redis->connect($v['host'], $v['port']);
    return $redis;
}, $redisHosts);

// Create an instance of locker
$locker = new Locker();


$path = tempnam(sys_get_temp_dir(), 'wise-locksmith-flock-');
$fileHandler = fopen($path, 'r');

$res = $locker->flock($fileHandler, function () {
    // Write the code you want to protect here
});

unlink($path);

return $res;


$res = $locker->redisLock($redisInstances[0], 'redisLock', function () {
    // Write the code you want to protect here
});

return $res;


$res = $locker->redLock($redisInstances, 'redLock', function () {
    // Write the code you want to protect here
});

return $res;


$res = $locker->channelLock('channelLock', function () {
    // Write the code you want to protect here
});

return $res;

use Pudongping\WiseLocksmith\Exception\WiseLocksmithException;
use Pudongping\WiseLocksmith\Locker;

try {
    $locker = new Locker();
    // ...
} catch (WiseLocksmithException $exception) {
    var_dump($exception->getPrevious());
    var_dump($exception->getCode(), $exception->getMessage());
}