Archive for the ‘php’ Category
5 tips to make your PHP code beautiful (3)
Avoid unnecessary control structures.
Brackets everywhere. Try to get rid of those as much as you can. Unnecessary brackets add visual complexity and make your code much longer. In real world situation, when you need to quickly browse through your code, they just add clutter
//prints out the structure of a table
function describe( $table )
{
$query = "SHOW COLUMNS FROM `$table `";
$result =mysql_query( $query );
if ( ! $result )
{
return $result;
} else {
$data = array();
while ( $record = mysql_fetch_assoc( $result ) )
{
$data[] = $record;
}
return $data;
}
}
In the function above the if-else structure is not needed, just because when $result is false I can just return it, breaking the flow. Also while ( $record = ..) uses brackets for looping over just one statement.
We can make describe() look much more tidy:
function describe( $table )
{
$query = "SHOW COLUMNS FROM `$table `";
$result =mysql_query( $query );
if ( ! $result ) return $result;
$data = array();
while ( $record = mysql_fetch_assoc( $result ) ) $data[] = $record;
return $data;
}
Seems nicer, uh ? While one could think that’s just a detail, when code complexity grows, this kind of tricks can help you cutting it down.
5 tips to make your PHP code beautiful (2)
Thoughtful minimalism
Think about the most concise, clear and readable way to write the code your writing. Assume you were writing a function to get a file extension (.gif, .doc, etc.). You could be tempted to use string manipulation functions.
$filename = 'file.doc';
$dot_position = strpos( $filename, '.' );
if ( $dot_position !== false )
{
$extension = substr( $filename, $dot_position + 1 );
}
var_dump($extension)
It’s a lot of code for such a simple task. Beside that, files with multiple dots ( filename.with.dots.html ) won’t be handled properly.
$filename = 'file.doc'; $extension = array_pop ( explode( '.', $filename ) ); var_dump($extension)
The lesson here is to restlessy try to find the best solutions , even when you thought you knew how to accomplish the task. The one-liner above, is more easy to read and much less error-prone. It will work with file with multiple dots or with no extension without any problem. (note: you may want to filter $filename with basename() to avoid directory names dot to interfere).
I am gonna give another example - imagine you’re trying to print a different string for a bunch of pages on you’re site.
if ( $page_id == 32 || $page_id == 10 || $page_id == null )
{
echo 'inactive';
} else {
echo 'active';
}
While this code is pretty ok, you could note that $page_id is repeated one time for every page you want to set as inactive.
$inactive_pages = array( 32, 10, null );
if ( in_array( $page_id, $inactive_pages ) )
{
echo 'inactive';
} else {
echo 'active';
}
This way you can add exceptions just inserting a new element in $inactive_pages array. This will make easier refactor the code to read $inactive_pages from a configuration file or from a database.
In situations where you need to keep your code even smaller you could even write a one-liner (but don’t exceed with them, as many people find them less readable - and often they’re right):
echo in_array( $page_id, array( 32, 10, null ) ) ? 'inactive' : 'active';
5 tips to make your PHP code beautiful (1)
Get your brackets right
..and indent your code properly, always. Always give to each of your curly brackets their very own line.
I am taking a snippet from Kohana to demonstrate this.
(bad) What do you think of this code ?
if ( ! is_array($data)){
if (strpos($data, '[') !== FALSE)
{$data = preg_replace('/\[.*\]/', '', $data);
}$data = empty($data) ? array() : array('for' => $data);}
(not nice) This is much better
if ( ! is_array($data)){
if (strpos($data, '[') !== FALSE){
$data = preg_replace('/\[.*\]/', '', $data);
}
$data = empty($data) ? array() : array('for' => $data);
}
(sweet) A nicely formatted code should show like this. You can tell at a glance where your every if begins and ends.
if ( ! is_array( $data) )
{
if ( strpos( $data, '[') !== FALSE )
{
$data = preg_replace('/\[.*\]/', '', $data );
}
$data = empty( $data ) ? array() : array( 'for' => $data );
}
How to build an absolute url in php
Today, I was looking for a way to make an url absolute.
Ok, it’s easy. Guess I should think some good excuse for not being to able to do it in 5 minutes. The sad reality is I ended digging on google (again).
I am posting what I found, for (main, and) your reference. Read the rest of this entry »
A piece of story
What I found. Oh! Look, look !
As old-schoolers know Deja News, an historical Usenet repository was lately acquired by Google some year ago for Google Groups service, still conserves intact pieces of story of the web.
Searching in google for google groups php at the first place what I found is (suspance):
Rasmus Lerdorf’s first PHP stable release announce!!
Xdump: a little piece of my story as developer
I am slowly beginning to pull online docs and samples for Xdump.
Xdump was one debugging tool I had to develop for the reason that in some situations var_dump() simply is not enough.
Here’s the overview of xdump.
Of course one could say that as good programmer you should never ever findy yourself in such a situation which requires something more powerful than var_dump() or print_r(). I can understand this kind of point-of-view, but I found that real world not always is like that.
Today at work, for example, I had to add some functionality to a zen-cart installation. This is something var_dump simply cannot manage (without driving you crazy, I mean). Read the rest of this entry »
Need for Cache
After going through PhpThumb hell, I decided to develop one serious decent caching library for caching dynamically generated images. Read the rest of this entry »
Xdump
When working with large arrays/objects,with complex references beetween variables or (again) php’s built-in var_dump() e debug_backtrace() shows their limits.
Have you ever tried to var_dump $GLOBALS ?
Even if when I started this lib there were already some classes which provided nice html formatted dump, in the moment I needed one, I couldn’t (my fault) find one. Read the rest of this entry »
