Skip to content

Instantly share code, notes, and snippets.

@hoffigk
Created April 5, 2013 20:18
Show Gist options
  • Save hoffigk/5322299 to your computer and use it in GitHub Desktop.
Save hoffigk/5322299 to your computer and use it in GitHub Desktop.
<?php
function createFoo()
{
$pdo = new PDO(/*...*/);
$maxTryCount = 3;
$tryCount = 0;
create_foo_start:
try {
$key = createMyOwnUniqueKey(); // e.g. foo-ear62-re4it
$stmt = $pdo->prepare('INSERT INTO foo (key) VALUES (:key)');
$stmt->execute(array(':key' => $key));
return new Foo(/*...*/);
} catch (PDOException $e) {
if (preg_match('Duplicate entry.*for key \'key\'', $e->getMessage())) {
if ($tryCount++ < $maxTryCount) {
goto create_foo_start;
}
throw MyKeyIsNotReallyUniqueException('oh ein eichhörnchen. ich muss weg ...');
}
throw new FooCreationException;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment