Using igorw/retry to handle collision of Uuid
While the Uuid collide probability is almost zero, and only happen when you have a very very very bad luck, there is always a chance for it. If you’re using PHP, I encourage to use igorw/retry! You can retry your process as many as your wish!
Let’s grab it by adding into composer require :
composer require "igorw/retry:dev-master"
And as demo, I’m going to use “rhumsaa/uuid”, we can add again in composer require :
composer require "rhumsaa/uuid:~2.8"
Great!, let's use it :
require 'vendor/autoload.php'; use function igorw\retry; use Rhumsaa\Uuid\Uuid; $uuid = Uuid::uuid4(); $uuidStr = $uuid->toString();
Now, the Uuid instance and its string random generation created, so we can use it in retry.
$i = 0; // retry maximum : 5 times until succeed retry(5, function () use ($uuid, $uuidStr, &$i) { $i++; if ($i > 1) { $uuidStr = $uuid->toString(); } // this is pseudo code $this->db('user')->insert([ 'id' => $uuidStr, 'name' => 'foo' ]); });
When your insertion failed and got exception, it will silently ( doesn’t show error message ) and do re-try again with new string generation instead and stop when it succeded. You can change how many retry by changing 1st parameter in retry function.
References :
Hey,
Nice post. Good practical usage of retry . One question I have is why do you need the $i, and $uuidStr to be passed ? It seems we can do like
use function igorw\retry;
use Rhumsaa\Uuid\Uuid;
$uuid = Uuid::uuid4();
retry(5, function () use ($uuid) {
$uuidStr = $uuid->toString();
$this->db('user')->insert([
'id' => $uuidStr,
'name' => 'foo'
]);
});
yes, that’s to make sure it works with initialize $uuidStr.