PHP code example of amiralii / laravel-redlock

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

    

amiralii / laravel-redlock example snippets

 
 use Amiralii\RedLock\Facades\RedLock;

 $product_id = 1;

 $lock_token = RedLock::lock($product_id, 3000);
 
 if ($lock_token) {

     $order->submit($product_id);

     RedLock::unlock($lock_token);
 }
 
 use Amiralii\RedLock\Facades\RedLock;

 $product_ids = [1, 2, 3, 5, 7];

 $lock_token = RedLock::lock('order-submitter', 3000);
 
 while ($product_ids && $lock_token) {

     $order->submit(array_shift($product_ids));

     $lock_token = RedLock::refreshLock($lock_token);
 }

 RedLock::unlock($lock_token);

 use Amiralii\RedLock\Facades\RedLock;

 $product_id = 1;

 $result = RedLock::runLocked($product_id, 3000, function () use ($order, $product_id) {
     $order->submit($product_id);
     return true;
 });

 echo $result ? 'Worked!' : 'Lock not acquired.';

 use Amiralii\RedLock\Facades\RedLock;

 $product_ids = [1, 2, 3, 5, 7];

 $result = RedLock::runLocked($product_id, 3000, function ($refresh) use ($order, $product_ids) {
     foreach ($product_ids as $product_id) {
         $refresh();
         $order->submit($product_id);
     }
     return true;
 });

 echo $result ? 'Worked!' : 'Lock lost or never acquired.';

use Amiralii\RedLock\Traits\QueueWithoutOverlap;

class OrderProductJob
{
    use QueueWithoutOverlap;

    public function __construct($order, $product_id)
    {
        $this->order = $order;
        $this->product_id = $product_id;
    }

    public function handleSync()
    {
        $this->order->submit($this->product_id);
    }

}

use Amiralii\RedLock\Traits\QueueWithoutOverlap;

class OrderProductsJob
{
    use QueueWithoutOverlap;

    protected $lock_time = 600; // 10 minutes in seconds

    public function __construct($order, array $product_ids)
    {
        $this->order = $order;
        $this->product_ids = $product_ids;
    }

    // We need to define getLockKey() because $product_ids is an array and the
    // automatic key generator can't deal with arrays.
    protected function getLockKey()
    {
        $product_ids = implode(',', $this->product_ids);
        return "OrderProductsJob:{$this->order->id}:{$product_ids}";
    }

    public function handleSync()
    {
        foreach ($this->product_ids as $product_id) {
            $this->refreshLock();
            $this->order->submit($product_id);
        }
    }

}