Code Design

Code design is important. Creating maintainable code is a matter every php developers should know about, there are so many PHP scripts out there that can be refered to as Spaghetti Code. To write nice code, you need to know about code design.

Create a set of rules

When starting to write PHP code, create your own set of coding rules, that also includes:

Commenting

When to use /**/ comments, when to use // and # as comments.

When creating comments for your code ( including doxygen formated comments ) you should think of a pattern that explains much feature in small amount of words.

Single/Double Quotes

When to use double/single quotes.

First you will need to learn when to use double and when to not use it. In some cases you might want to use double quotes for a cleaner code. Take this example in consideration:


// Not so readable ( but optimize a tad performance )
$hi = 'Hi ' . $var . 'wo' .$r .'ld' . $var2 . $var3 . '!';

// More readable
$hi = "Hi {$var} wo{$r}ld{$var2}{$var3}!";



Variable names

Is it OK to use: $c when the name can be $car ?

Think of a smart way of naming your variables, it's a bad idea to make $c refer to "a car object that is not having a door" - a better solution might be $carWithoutDoor = new Car(Car::NO_DOOR);

Function/Method names

This can not be stressed enough, are you using camelcase hiThereMan or underscore seprator: hi_there_man. PHP developers who created PHP got this mixed up, and this is very confusing and a lot of people complain about it!.

Me myself and many more prefer camelcase, it's easy to write and lets you use the underscore for other patterns you might have.

One class in 1 file

Separate classes into class name of file name. Forexample class HiPeople can be put in HiPeople.php.

MVC

Use MVC design pattern, Separating View logic, Controller logic and model logic will make your application a pleasure to work with.

Be consistant

When you first have your coding design pattern - use it over the whole application, make new developers read your own "coding rules" -in this way you will allways be sure that the application keeps a consistant code design. This results in code easier to read!

Please write the code you see on this image:

Human verification