PHP code example of latrell / lock

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

    

latrell / lock example snippets


    'providers' => [
        // ...
        Latrell\Lock\LockServiceProvider::class,
    ]

    'aliases' => [
        // ...
        'Lock' => Latrell\Lock\Facades\Lock::class,
    ]

// 防止商品超卖。
$key = 'Goods:' . $goods_id;
Lock::granule($key, function() use($goods_id) {
	$goods = Goods::find($goods_id);
	if ( $goods->stock > 0 ) {
		// ...
	}
});


// 锁名称。
$key = 'Goods:' . $goods_id;

// **注意:除非特别自信,否则一定要记得捕获异常,保证解锁动作。**
try {

	// 上锁。
	Lock::acquire($key);

	// 逻辑单元。
	$goods = Goods::find($goods_id);
	if ( $goods->stock > 0 ) {
		// ...
	}
} finally {
	// 解锁。
	Lock::release($key);
}