-
-
Save DracoBlue/5358443 to your computer and use it in GitHub Desktop.
goto without goto ;)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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