PHP code example of ivanomatteo / laravel-db-mutex
1. Go to this page and download the library: Download ivanomatteo/laravel-db-mutex 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/ */
ivanomatteo / laravel-db-mutex example snippets
// add HasDbMutex trait to your model
use HasDbMutex; // ( IvanoMatteo\LaravelDbMutex\HasDbMutex )
$m = YourModel::find(1);
$m->usingDbMutex(function(){
// this code will run in mutual exclusion
// for all request calling it
// on the record with id 1
sleep(5);
echo "done!";
});
$m->usingDbMutex(function(){
// this code will run in mutual exclusion
// for all request calling it
// on the record with id 1, with "foo" identifier
sleep(5);
echo "done!";
},null,"foo");
$m->usingDbMutex(function(){
/*
in this case we will use also an optimistic lock mechanism
we can provide the previous value of
- counter
more reliable but slower, the counter value since is incremented inside a "read lock"
can't never be the same
and/or
- model_updated_at (updated_at timestamp of the model)
can be used if you are making modification on the model
(model_updated_at would not make sense if your modifications are applied only to someting else)
less reliable but faster, the updated_at field of the model
can be read outside of the "read lock"
if the values do not match the currents, a 412 http error will be returned
NOTE: these values must came from the current REQUEST, not from the retrieved models
*/
},
[
'counter' => 10,
'model_updated_at' => '2020-12-28 14:56:44',
]
);
// in the case, you want to use the counter value, obviously you need to load the previous value
// when reading the data. You could you use withDbMutex scope as explained below.
// there is also the withDbMutex scope
YourModel::withDbMutex()->find(1); //will add the "default" dbmutex data
YourModel::withDbMutex('foo')->find(1); //will add the "foo" dbmutex data
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.