I was wondering, what problems have you come across that have made you rush to your IDE of choice and code away?
I’m sure that I’m not the only one that needs a problem to solve before things become interesting. Given the nature of us forum folk, I would guess most of the long standing folk hang around, just waiting for a problem to solve.
Here’s mine tonight, I’ve spent a full night researching, learning, then solving this problem.
Sometimes it’s nice to be reminded why we stick at this stuff.
So there I was, as usual, browsing Sitepoint and this feature really irked me. In conjunction with [URL=“http://www.sitepoint.com/forums/showthread.php?t=628752”]this thread, it seemed people were fine with a loop that constantly queried a database to see if a value already existed until they found one that didn’t.
It just screamed to breach DRY and I set about tonight finding a way to solve this.
In the end, I created a class to encode the id provided by the database after record insertion (always unique) to generate this unique value (al la Short URL services).
For completeness, here is class.
<?php
/**
* @author Anthony Sterling
*/
class Base62
{
/**
* @desc Holds the key used to encode and decode.
*
* @var Array
*/
protected static $aCharMap = array(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9'
);
/**
* @desc Encodes an integer to Base 62
*
* @param Integer $iInteger
* @return String
*/
public static function Encode($iInteger)
{
$sString = '';
while($iInteger > 0)
{
$sString .= (string)self::$aCharMap[$iInteger % 62];
$iInteger = floor($iInteger / 62);
}
return $sString;
}
/**
* @desc Decodes a Base 62 encoded string
*
* @param String $sString
* @return Integer
*/
public static function Decode($sString)
{
$aFlippedMap = array_flip(
self::$aCharMap
);
$iInteger = 0;
for($iCurrentPosition = 0; $iCurrentPosition < strlen($sString); $iCurrentPosition++)
{
$iInteger += $aFlippedMap[$sString[$iCurrentPosition]] * pow(62, $iCurrentPosition);
}
return $iInteger;
}
}
$iInteger = 2147483647;
$sEncoded = Base62::Encode($iInteger);
$iDecoded = Base62::Decode($sEncoded);
header('Content-Type: text/plain');
printf(
"
Attempting to Encode:\ %d
Encoded Value:\ \ %s
Decoded Value:\ \ %s
",
$iInteger,
$sEncoded,
$iDecoded
);
/*
Attempting to Encode: 2147483647
Encoded Value: bLMuvc
Decoded Value: 2147483647
*/
?>
So, have you had any moments like this? If so, what was the problem then approach/code did you apply to the problem in hand?
Thanks all,
Anthony.