PHP code example of cheprasov / php-memcached-lock

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

    

cheprasov / php-memcached-lock example snippets



MemcachedLock\MemcachedLock;

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

$Lock = new MemcachedLock(
    $Memcached, // Instance of Memcached,
    'key', // Key in storage,
);


MemcachedLock\MemcachedLock;

// Create a new Memcached instance
$Memcached = new \Memcached();
$Memcached->addServer('127.0.0.1', '11211');

//...

/**
 * Safe update json in Memcached storage
 * @param Memcached $Memcached
 * @param string $key
 * @param array $array
 * @throws Exception
 */
function updateJsonInMemcached(\Memcached $Memcached, $key, array $array) {
    // Create new Lock instance
    $Lock = new MemcachedLock($Memcached, 'Lock_'.$key, MemcachedLock::FLAG_CATCH_EXCEPTIONS);

    // Acquire lock for 2 sec.
    // If lock has acquired in another thread then we will wait 3 second,
    // until another thread release the lock. Otherwise it throws a exception.
    if (!$Lock->acquire(2, 3)) {
        throw new Exception('Can\'t get a Lock');
    }

    // Get value from storage
    $json = $Memcached->get($key);
    if (!$json) {
        $jsonArray = [];
    } else {
        $jsonArray = json_decode($json, true);
    }

    // Some operations with json
    $jsonArray = array_merge($jsonArray, $array);

    $json = json_encode($jsonArray);
    // Update key in storage
    $Memcached->set($key, $json);

    // Release the lock
    // After $lock->release() another waiting thread (Lock) will be able to update json in storage
    $Lock->release();
}


$Lock = new MemcachedLock($Memcached, 'lockName');
// or
$Lock = new MemcachedLock($Memcached, 'lockName', MemcachedLock::FLAG_USE_SELF_EXPIRE_SYNC);
// or
$Lock = new MemcachedLock($Memcached, 'lockName',
    MemcachedLock::FLAG_CATCH_EXCEPTIONS | MemcachedLock::FLAG_USE_SELF_EXPIRE_SYNC
);


$Lock = new MemcachedLock($Memcached, 'lockName');
$Lock->acquire(3, 4);
// ... do something
$Lock->release();

$Lock = new MemcachedLock($Memcached, 'lockName');
$Lock->acquire(3, 4);
// ... do something
$Lock->update(3);
// ... do something
$Lock->release();