We now have an awesome page set up. Let’s add some logic to it! Open up your model and controller files and let’s get going! First we’ll pump up our model to generate and test both the md5 of the url and the unique random code associated with the shortened url. So open up the model file, shorten.php and add:
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function getFilename($length=8, $prefix=''){ $string = ""; $possible = "abcdefghijklmnopqrstuvwxyz0123456789"; $i = 0; do { while ($i < $length) { $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); if(rand(0,1)){ $char = strtoupper($char); } $string .= $char; $i++; } } while (file_exists(sprintf($prefix, $string)) == true); return $string; } |
What does this do? Well it generates random strings, of both lower and upper cases from the alphabet. It also checks to see if the code exists already in the database, and if it does, to generate another one, until it finds one that is aok to use! This function will come in handy later on when we actually insert the url record into the database. Next let’s write a function that md5’s the url if it doesn’t exist already, and if it does, to tell us the url exists already:
25 26 27 28 29 30 31 32 33 34 | function md5Url($url){ $md5edurl['url'] = md5($url); $md5search = $this->find('count', array('conditions'=>array('unique'=>$md5edurl['url'])), array('recursive'=>-1)); if($md5search > 0){ $md5edurl['exists'] = false; } else { $md5edurl['exists'] = true; } return $md5edurl; } |
False? why return false? Well let’s think about this for a moment. Think about what we want to do if the url already exists. We don’t want to save it again! So in effect, we return false that the url should not be re-saved. Instead it should be reused. This function is easy enough to understand. MD5 the url, then see if one exists in the database already. We store whether the url exists already in the exists element of the $md5edurl alongside the md5′d url!
Both of these functions however use a CakePHP function. The find command. It firstly has the find type, in our case both are counts, the conditions for its look up. However the last option might puzzle you a bit. Recursive is set to -1. This is if we had any table associations in place, we wouldn’t need them in these two look ups. CakePHP would automatically include joins on these tables, including data which we don’t need. Setting this recursive to -1 will lock CakePHP’s find to only that table! Easy!




2 trackbacks/pingbacks
Comments About CakePHP URL Shortener Service Tutorial
// 3 comments so far.
Elizabeth Gibbons // August 26th 2009
i have never seen such a comprehensive tutortial on this , good on yah, i’ll buy you a paypal beer any day
hendrik // August 31st 2009
great work, thank you!
JP // December 16th 2009
Awesome tutorial man! Thanks allot
You can follow any responses to this entry via its RSS comments feed. You may also leave a trackback by clicking this link.