PHP code example of friendsofphp / consul-php-sdk

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

    

friendsofphp / consul-php-sdk example snippets



$kv = new Consul\Services\KV();

$kv->put('test/foo/bar', 'bazinga');
$kv->get('test/foo/bar', ['raw' => true]);
$kv->delete('test/foo/bar');

$response = $service->method($mandatoryArgument, $someOptions);

$session = new Consul\Services\Session();

$sessionId = $session->create()->json()['ID'];

// Lock a key / value with the current session
$lockAcquired = $kv->put('tests/session/a-lock', 'a value', ['acquire' => $sessionId])->json();

if (false === $lockAcquired) {
    $session->destroy($sessionId);

    echo "The lock is already acquire by another node.\n";
    exit(1);
}

echo "Do you jobs here....";
sleep(5);
echo "End\n";

$kv->delete('tests/session/a-lock');
$session->destroy($sessionId);

$resources = ['resource1', 'resource2'];

$multiLockHandler = new MultiLockHandler($resources, 60, new Session(), new KV(), 'my/lock/');

if ($multiLockHandler->lock()) {
    try {
        echo "Do you jobs here....";
    } finally {
        $multiLockHandler->release();    
    }
}

$resources = [
    new Resource('resource1', 2, 7),
    new Resource('resource2', 3, 6),
    new Resource('resource3', 1, 1),
];

$semaphore = new MultiSemaphore($resources, 60, new Session(), new KV(), 'my/semaphore');

if ($semaphore->acquire()) {
    try {
        echo "Do you jobs here....";
    } finally {
        $semaphore->release();    
    }
}