Archive for December, 2009

Monday, December 14th, 2009

Clean, Tidy and Flexible Function Variables

The thing about functions is... they grow. They start off small and cute and useful, but over time you start to notice their little shortcomings, so you make them bigger, better, and more flexible. Unfortunately, if you're using PHP's default method of passing functions, which is based on the sequence the functions are given (i.e. function example($variable1, $variable2, $etc)) , things can get a little messy. The more variables a function can handle, the harder it is to remember the sequence they have to follow. Not to mention PHP 5 doesn't facilitate a way to skip variables. For example, this doesn't work: example($variable1, , $variable3, $etc).

The solution is to pass your variables on in an array. Here's the template that I use whenever I code a new function:
function example($args="") {
$variable1 = $args['variable1']? $args['variable1'] : 'default';
}

And this is how you pass variables on to your function:
$args = array(
'variable1' => 'value',
'variable2' => 2,
'variable3' => $etc
READ MORE»

View Comments

Wednesday, December 9th, 2009

Code your own permalinks

Ever wondered how a CMS like WordPress creates those pretty URLs that resemble directory structures on the fly?Ever wondered if you could do the same thing with your own website or web app? Well you can, and it's ridiculously simple.

Step 1: You need to edit your .htaccess file to incorporate some mod rewrite rules. This is the code that we're going to use (the same code that WordPress uses):


RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /yourcode.php [L]


What this does is capture the "filenames" (really just a URI string that comes after your site root), and pass them on in an array to the file of your choice, "yourcode.php" in this case. It does all this without changing the URL on the user's end. So now all we have to do is pick up those variables in our PHP code. We'll do that with this code in yourcode.php :


$uri = $_SERVER['REQUEST_URI'];
$vars = explode('/', $uri);


So now we've captured the elements of the permalink in our array $vars, starting with the second array object, $vars[1]. The first array object, $vars[0] will ... READ MORE»

View Comments

Copyright © 2009 Rajeev Singh