Apr
25
2010
PHP // web

20 Tips to Make Your PHP Code Better

The most used and well documented programming language for web development is PHP, but it has some problems as a language (every language does). The most important problem is it’s too much permissive, and we can make some common mistakes that can hide our program’s behaviour beyond the limit, instead of writing a clean and easy readable code.

The “limit” is something abstract and we can’t draw the line. But there are many other things and habits we can do and get into of right now to be better developers, 20 of those things are right here.

1. The var_dump is your friend

This function lets you know the value of a variable. Yes, I know, it can sounds pretty obvious, but because PHP is a dynamic language the debugging process can be hard ( it could cover a whole tutorial, actually) and just see the value with a function can help us for “debugging” in an easy way.

This is the specification of such an useful function. Just in case you don’t get the point, we can pass it more than one variable!

var_dump

If you are just using this function and not showing anything more you can pass as the first parameter the string “<pre>” and the output will be easier to understand.

2. Measure the time

When we are developing, we all need to know how much is going to “cost”, because that price must be paid by the user and by our server. Actually is very easy, let’s see a way to do this.

<?php
function timer_start() {
	global $timeparts,$starttime;
	$timeparts = explode(" ",microtime());
	$starttime = $timeparts[1].substr($timeparts[0],1);
	$timeparts = explode(" ",microtime());
}

function time_end() {
	global $timeparts,$starttime;
	$endtime = $timeparts[1].substr($timeparts[0],1);
	return bcsub($endtime,$starttime,6);
}
?>

These functions are required and a very clean way to do this. We can have them in a file, include it whenever we need to measure the time and just echo the result. Here is how:

<?php
include('time_helper.php');

time_start();

// here the code you want to measure
echo 'Hi over there!';

echo time_end();
?>

3. Respect your style

Everyone has his own style, the problem comes when sometimes we have to write code together, or worst, a guy after us have to do it, the point is he has no idea about how we think.

An important fact here is our brain learns better through patterns, so if we respect the same style, we have crossed the first door to get a cleaner code. But, what am I talking about when I say style? The following two examples have different style. Take a look at them.

<?php
function test($var1)
{
	if ($var1)
	//Checking if var1 is ok
	{
		echo "Var1 is Ok";
	}
}
$var2=5;
?>
<?php
function test($var1){
	//Checking if var1 is ok
	if ($var1){
		echo "Var1 is Ok";
	}
}

$var2 = 5;
?>

Yes, I know it could look pointless, but the position of comments or braces have to respect a pattern. Remember, our brain learns faster if we do that.

4. Naming with strong meaning

Spiderman, a man who is almost like a spider, easy right? Well, the name of our functions or variables must be too. Whenever we name something we have to think about its functionality and name it accordingly.

You have to be able to have a clue about the role of the function or variable every time you use it. So don’t name a variable with something like “$a” or “$a1″, better “$request_result” or “$first_element”, for example.

5. Research into the field

It’s important, as a developer, know the tools you have on your table. Maybe you are thinking about how to do a function to sort an array because you don’t know if it has already been made. Of course there isn’t a function for every single case, but PHP is growing up, and has got a lot of functions, so Google can comes in handy if you are wondering how to do a common thing in PHP scripts.

You can also download a cheat sheet, which can show you at first sight the power of the tool you are working with.

6. Booleans could be complicated

If you have got a boolean variable, name it in an afirmative way. Just like the first example.

<?php
// Good and cleaner way
$enable = false;
if (!$enable)
	echo "Ok";

// Bad way. This is just if($enable)
$disable = false;
if (!$disable)
	echo 'Not ok';
?>

7. Copy and Paste are developers’ devils

Just two commands can waste a whole morning. I’m not saying we have to reinvent the wheel every time we type, but we always have to read and completely understand the code we are using.

Say we don’t do this, and we see a code similar to the code we want and without even reading it we just put in the middle of our script. Well, if you realize is like putting a spare part in our car without seeing it. If the car breaks down it’s justified, isn’t it?

A program is like a car, so take cares of him, and don’t let anything crosses the door without researching it before.

8. Getters and Setters

A class must respect some patterns too, like our style. A widely extended practice is mark the attributes as privates and if we want to make them public, we make its getter and setter functions.

See the example below, where we don’t want the rest of classes to know who the owner is, but we don’t care about they know the animal’s name, so we use this practice:

<?php
class animal{
	private $owner;
	private $name;

	// Getter
	public function get_name(){
		return $this->name;
	}

	// Setter
	public function set_name($string){
	   $this->name = $string;
	}
}
?>

9. Exceptions are useful

An exception sounds like an ugly thing, in fact every time we’ve got one means something is wrong and we have to fix it. But exceptions in a script can save a lot of time typing code and checking it.

When something can go wrong (almost always) we have to say to someone (the user or other program), at least the error and the reason why it happened. Exceptions can be very useful here, and using them is a must.

10. Divide to rule them all

A common explication for the students at University is that a program is just a set of boxes, the way the boxes have to communicate something is just their output (commonly return).

Well, this definitions is very abstract, but also very useful, we have to think about boxes when we are programming, and if some lines share an objective, we have to make a function and put them there. See this couple of snippets, and judge for yourself.

<?php
// Bad way
$int_array = array(1,9,10,12,7,2,8);    

echo "We have to order this array" . "<br />";
foreach($int_array as $value){
	echo $value . "<br />";
}        

sort($int_array);

echo "The output is:" . "<br />";
foreach($int_array as $value){
	echo $value . "<br />";
}
?>

And the good way:

<?php
// Good way
$int_array = array(1,9,10,12,7,2,8);    

function print_array($array){
	foreach($array as $value){
		echo $value . "<br />";
	}
}

echo "We have to order this array" . "<br />";
print_array($int_array);

sort($int_array);

echo "The output is:" . "<br />";
print_array($int_array);
?>

Of course this is a fool example, because there is a way to do this with some built-in functions (var_dump, for instance), and the script doesn’t do too much work, but the point here is you can see the function “print_array” is saving us writing again the same code and the script, at first sight, looks cleaner.

11. Coding is important

Even essential if in your language there are characters like é, ó, ñ…etc. And not because of the code itself, the key are the comments or some html if you are printing it from a PHP script.

If you change the coding you can create a mess, so every time you are starting or modifying a project you need to check your editor is using exactly the same coding than the project.

I could say just don’t use weird symbols, but it’s not always possible, so be careful.

12. Comments are as important as the code is

I don’t want you to think I’m crazy, but imagine you develop a complex script, without a single comment, if someone is going to reuse it some months later, even you, and an error comes up, fixing the problem is going to take a lot of time just trying to understand the code plus fixing the problem itself.

There is a way to comment which can helps, because it’s very extended and almost every developer understands. You can see all the docs at the conclusion, but basically we’ll have some “special parameters” starting with @, like @see to refer another function, @return to specify the type of the the variable the function is going to return….etc. (You can see all of them in the link at the conclusion)

A good thing about using this format is you can use a tool and export the documentation as a pdf, html or another file, even from the IDE itself you are using (most IDE’s can do this).

12. Be independent

Your code must be a box, and a box doesn’t care about the rest of boxes, so your functions and classes shouldn’t do.

When we write a class we have to think the only way the user has to know something which could happen inside our class is up to us, so we have to do it as better as we can, and make developers’ life easiest (not only ours).

The better thing we can do is making a “map” of errors, and name them with a code and a description. When we have got an exception we return the specified error code. Of course our decisions aren’t standard, so we have to explain the code we’ve invented in the comments

13. An interface is a gift

When we have got a class, and the functions return really useful messages, we are very very lucky, because most developers returns values almost cryptic, and there is no reason apart from laziness to do this.

So every time we have to return something, or display a message, think the best and cleanest way to do that.

14. Official documentation is the only reliable source

Internet is a huge source of information, but in technical stuff, we have to be very carefully and don’t trust anyone, actually if you have got a doubt about a function, which is perfectly usual, it’s better looking up only in the official site.

documentation

15. Use of variables

In a programming language where we declare a variable with just a line, there is a risk of having too much and some pointless variables.

That’s exactly what happens in PHP when our program starts to grow. We should have variables, apart from well named, with a well known role in the script, and if we use an “aux” variable, taking care of not reusing it.

It’s not about the number of variables we can have, it’s about we need to know them all very well, and the reason why they exist.

16. Family is cool

At least in a programming context. PHP is an OO language, so not using heritage in our programs it’s almost an offense for an object oriented language like PHP. Let’s see how to do it, in the first example we can see the bad way:

<?php
class Person
{
    private $givenName;
    private $age;
}

class Employee
{
    private $givenName;
    private $age;
}
?>

And the good way should be something like:

<?php
abstract class Person{
    private $givenName;
    private $age;

	// Getters and setters
    public function set_givenName($name){
        $this->givenName = $name;
    }

    public function get_givenName(){
        return $this->givenName;
    }

    public function set_age($age){
        $this->age = $age;
    }

    public function get_age(){
        return $this->age;
    }

    public function say_hello(){
        echo("I am ");
        $this->print_data();
    }

	// The son will define this function according to its features
   	abstract public function print_data();
}

class Employee extends Person{
    private $role;

	// Getters and setters
    public function set_role($r){
        $this->role = $r;
    }

    public function get_role(){
        return $this->role;
    }

    /*This class have all the public and protected methods from
	the class Person*/
    public function print_data(){
        echo($this->getRole() . " " . $this->get_givenName() . " and I am " .
            $this->get_age() . " years old");
    }
}
?>

17. Functions should be small

If you have got a function where you need to scroll down to see its end, probably you should be thinking how to split it into smaller functions.

18. Frameworks can save you a lot of work

Frameworks are friends who can make for you the dirty work. There are many of them, probably the most used ones are CodeIgniter, Zend or CakePHP, but it’s up to you watch some screencast and study some tutorials to choose the one which should be better for the project we are working on.

If you are starting with frameworks in PHP I recommend you CodeIgniter, it has a great documentation, and develop with it it’s very easy.

CodeIgniter can save you a lot of work

19. Regular expressions are always useful

In every project, if it’s a little bit big, regular expressions will always come in handy.

Since removing repeated words in a text to extracting data from a raw format are only some tasks very easy to do with regular expressions. PHP has a set of functions to do that and know regular expressions and this functions can save you a lot of time, and even make the code cleaner.

20. Common sense above everything

This advices are only useful if you understand them, and try always to use your common sense. How to name variables, or comment the code are just some task where you should be using your common sense, so don’t forget we program for computers but also for human beings.

Conclusion

Like everything else in life you should learn as much as you can about the tools you are working with, and it takes a lot of time to become a better developer in any programming language, so be patience and remember, common sense and documentation are your best allies.

Leave a comment