Why are php coding guidelines important

2007-11-02

A small guide on how to write your own coding guidelines for php projects and why is important to respect them.

Coding guidelines are very important for a project, especially for a project where more than a programmer takes part.

A coding guideline is a set of rules that everybody involved in that specific project must obey in order to develop it successfully.

Web development is a medium where a lot of languages and technologies are involved. Without a set of rules there is a risk of "junk" code (code that can not be easily maintained) to be written.

In the following part I will show you the coding guidelines I use for my php + mysql projects.

Document your project with phpdoc

One of the most important thing is to document your code so that somebody else that will look at your code can easily understand it. Writing your comments in the PHPDoc format can help you a lot because it can generate a complete documentation for your project from the comments.All PHPDoc comments start with "/**" instead of the normal "/*"

Class documentation

Describe the class purpose and write the appropriate @package name. Describe the purpose of all variables of your class and their access modes.


/**

 * MVC Controller

 *

 * This Class implements MVC Controller part. It is implemented as a singleton.

 *

 * @package MVC

 * @subpackage Controller

 * @author John Doe 

 * @copyright CodeAssembly

 * @version 1.0

 */

class Controller

{

#

   /**

   * Holds the name of the currently running module

   * 

   * @access private

   *	

   * @staticvar string

   */

   static private $moduleName;

   /**

   * Holds the name of the currently running action

   * 

   * @access private

   * @staticvar string

   */

   static private $actionName;

   /**

   * Holds all variables passed to the current action

   * 

   * @access private

   * @staticvar array

   */

   static private $params;

Function and class methods documentation

Write a small description of the function. Describe each parameter and return value.


/**

* Redirect or direct to a action or default module action and parameters

* it has the ability to http redirect to the specified action

* internally used to direct to action

*

* @param string $moduleName this is the module to witch the redirection will occur

* @param string $actionName this is the module to witch the redirection will occur

* @param array $parameters additional parameters to be passed to the action

* @param bool $httpRedirect do a http redirect, if true it uses header('Location:') to redirect, otherwise will call the action directly

* @return bool returns true if successful false otherwise

*/

function redirect( $moduleName , $actionName , $parameters = null, $httpRedirect = false )

{

.

.

}

For more information about PHPDoc visit PHPDoc documentation page

Code layout and guidelines

Having everyone in the team writing the code in the same way makes it easy for everyone. This is my style. You can decide on a common style on your own.

Variable Names

I like java style naming convention where the first letter of the first word is lower case and all other words in the variable starts with a uppercase letter.You can also use the small case and separate the words with "_" character.


/*

The style that I use

*/

$moduleName;

$

/*You can also use this style*/

$module_name;

Try to keep your variables short, but not too short, good examples are variables with maximum 3 words like $userNameId

Function naming

I apply the same rules as the ones from variables except that here I can use more than 3 words. You can try using less words, but don't hurt the function name, it must be obvious what it does.function getUserNameId( $userName )

Braces

Always use braces. Even for one instruction, this makes the code easier to read. Put braces on a newline and make them match (put them on the same column).




if () 

{

	while ()

	{

		for () 

		{

			doSomething();//just one instruction and we still use braces

		}

	}

}



function fooBar() 

{

}

Use space between tokens

Code without space between the tokens is hard to read. Try to use space between them every time, it takes time to get used to but it pays off.


//hard to read

function someFunction($firstVariable,$secondVariable)

//easy to read

function someFunction( $firstVariable, $secondVariable )



//hard to read

$variable="Some text";

//easy to read

$variable = "Some text";



//hard to read

for($i=0;$i<$count;$i++)

//easy to read

for( $i = 0; $i < $count; $i++ )



//hard to read

$variable=$first.$second.$third.'text';

//easy to read

$variable = $first . $second . $third . 'text';

Properly indent code

Use tabs instead of spaces. In this way everyone can set his favorite editor to display tab space to his own will. Indent every block of code so it can be easily readable.


//a small code portion from my own MVC.

if ( $moduleName === false or ( $moduleName === self :: $moduleName and $actionName === self :: $actionName ) )

{

	return self :: $params;

} else

{

	if ( $actionName === false )

	{

		return false;

	} else

	{

		@include_once ( FRAMEWORK_PATH . '/modules/' . $moduleName. '.php' ) ;



		$method = new ReflectionMethod( 'mod_' . $moduleName , $actionName );



		foreach ( $method -> getParameters() as $parameter )

		{

			$parameters[ $parameter -> getName() ] = null;

		}



		return $parameters;

	}

}

Inline conditionals

Don't use inline conditionals because it can hurt code readability, try to avoid them at all costs.


//for long statements it can be confusing

( $i < $j || $i > 0 ) ? someFunction( $i ) : someFunction( $j );



//is easier to read 

if ($i < $j || $i > 0 ) 

{ 

	someFunction( $i ) 

} else

{

	someFunction( $j );

}

Optimize your code

Use a variable for loop conditions to avoid unnecessary calculations


//"sizeof" is called for each iteration and slows down the loop

for ( $i = 0; $i < sizeof($myArray); $i++ )

{

	someFunction();

}

//"sizeof" is called only once on the first iteration

for ( $i = 0; $i < $count = sizeof($myArray); $i++ )

{

	someFunction();

}

Don't use double quoted strings "" unless you have some $variables inside, because when using double quoted strings, php searches for variables inside the string and this is slower than single quoted strings ''. Use double quoted strings when including variables, don't use single quotes strings and concatenation because it hurts readability.


//this is a bit slower

$variable = "Some text";

//than this

$variable = 'Some text';

//correct usage of double quoted strings

$variable = "Hello $userName";

//wrong usage of single quoted strings

$variable = 'Hello ' . $userName;

Sanitize user input

Make sure your application is secure, and sanitize all user input. This includes $_GET, $_POST and $_COOKIE super globals. There are many ways for doing this. You can build your own class or functions, but the best way is to use php filter.Do this at the beginning of each script that has user input and before form submitted data processing.


//filter username variable from $_GEt super global

$userId = filter_input(INPUT_GET, 'userid', FILTER_REQUIRE_SCALAR );



//filter username variable from $_POST super global

$userName = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_SPECIAL_CHARS);

Use a MVC (Model-view-controller) framework to separate business logic from presentation logic

Don't mix business logic (only php) with presentation logic (html and some php). Making this mistake will hurt the maintenance of the application and it will make a skin replacement for your site a nightmare. You can use a simple php template engine, but a full featured MVC framework is recommended. There are many good MVC frameworks out there, here are some of them: Zend framework, Symfony framework CakePHP framework, search for more on Google, or you can roll out your own. After understanding the concept well enough, read about MVC framework

Use database abstraction

Don't make your application specific for just one RDBMS (relational database management system ), use a database abstraction class. If you use a MVC framework then it surely comes with such a class, if you use just a template engine then you can try some database abstraction classes like ADODB. Using such a class will help you migrate your application to a another RDMBS easier when your application grows or when your hosting has another RDBMS installed.

File structure

Have a good file structure, keep your scripts organized so you know where to search when you need something. Keep your html in their own folder, images in a separate folder, php scripts in another folder etc. Here is my file structure

"Modules" directory contains my php scripts, views contains html templates and the others are self explanatory.

HTML coding

Use XTHML instead of HTML, it's XML compatible. Keep your styles out of html, put all your style in an external css file. Write semantically correct html code

Good luck in writing your projects.

Share this with the world

Related

Comments

Harald

i agree with most of your points, even though i don't like your coding-guidelines. but that's a very subjectiv point of view ;-). however:

in projects where you will not only have php code but javascript, perl, shell, whatever else phpdoc might not be the best solution, because i think the source-code documentation should look the same across all languages. i've tried several solutions for this and are now using robodoc, which i like very much. it won't analyse your source-code and therefore most time it's a lot more to write to document your code. on the other hand you have unified documentation for all your source-files - and i mean really all: you can even write documentation for your configuration-files for example.

Posted on 2007-11-06 13:57:06
Dadaso

Really useful to develop project

Posted on 2007-11-15 07:22:08

Make yourself heard

Categories

Subscribe

All Posts

Php posts

All Comments

This post comments

© Copyright CodeAssembly

All code is licensed under GPL, unless otherwise noted