Skip to content

Instantly share code, notes, and snippets.

@DracoBlue
Forked from hoffigk/my-first-goto.php
Last active December 16, 2015 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DracoBlue/5358443 to your computer and use it in GitHub Desktop.
Save DracoBlue/5358443 to your computer and use it in GitHub Desktop.
goto without goto ;)
<?php
function createFoo()
{
$pdo = new PDO(/*...*/);
$maxTryCount = 3;
$tryCount = $maxTryCount;
while ($tryCount > 0)
{
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) {
$tryCount--;
if (!preg_match('Duplicate entry.*for key \'key\'', $e->getMessage())) {
/* oh noes, we have a PDO exception, but it does NOT contain a Duplicate-Info ... so not worth a retry, DIE!! */
throw new FooCreationException;
}
}
}
/* We tried it $maxTryCount */
throw MyKeyIsNotReallyUniqueException('oh ein eichhörnchen. ich muss weg ...');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment