ez.no / ezpublish / documentation / development / standards / php
These documentation pages are no longer maintained. Please visit the new documentation site.
This document defines how the PHP code in eZ publish is formatted. Naming conventions are also defined in this document. The code in eZ publish must follow this standard to ensure a coherent looking code base.
For easier comply with this coding standard we recommend using emacs with our configuration files which handles proper indenting and other nice features.
Use lower-case in all file names. PHP files are named .php
All files must start with the following header:
// Created on: <nn-Mmm-YYYY HH:MM:NN username> // // SOFTWARE NAME: eZ publish // SOFTWARE RELEASE: n.n.n // BUILD VERSION: nnnnn // COPYRIGHT NOTICE: Copyright (C) 1999-2006 eZ systems AS // SOFTWARE LICENSE: GNU General Public License v2.0 // NOTICE: > // This program is free software; you can redistribute it and/or // modify it under the terms of version 2.0 of the GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of version 2.0 of the GNU General // Public License along with this program; if not, write to the Free // Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA. // //
Indenting is 4 characters, real tab characters should not be used. Spaces are used for indenting.
Start and end brackets should be placed on the same column.
Examples:
multiply( $x, $y ) { // function body } if ( x == y ) { .. } else if ( x > y ) { .. } else { .. } class foo { function foo( ) { .. } }
It should always be a space after a start parenthesis and one space before an end parenthesis. One space is placed after every comma. Square brackets [] should not have space after the start bracket and before the end bracket. It should be a space between each type.
Empty lines should be used to group variables and code lines which have a connection. Variable names which is grouped should be indented to the same level.
Empty lines should not only appear empty, but they should also be empty, all tab and space characters should be removed. Unnecessary trailing white-spaces should also be removed.
Use more parenthesis than necessary if you're not certain in which sequence the expression is executed.
PHP has many different ways of handling strings. Some are preferred because of speed, others because of readability of code.
PHP has two different quotes " and '. These are used to define a text string. The difference between the two is that the single quote does not process the string or does variable replacement. I.e. if you write "$myVariable\n" and '$myVariable\n' the first will print the contents of the variable followed by a newline character. The latter will print: $myVariable\n, with no aditional processing. For this reason you should use single quotes rather than double quotes because this will be quicker. If you need to have a combination of text and variables you should use the implode() function. This function should be used instead of the . operator since this does only allocate memory once and is therefore more efficient.
Below is samples of how you should use single quotes in eZ publish.
$myHash['key']; $str = 'This is a string'; $combinedString = implode( '', array( 'The color of the ball is ', $color, ' and it costs: ', $price ) ); if ( $variable == 'string' ) { .. }
While PHP supports any case on the boolean types and the null type they should always be written in lowercase.
Example:
$isSet = true; $canPrint = false; $unset = null;
Nested if statements should always use {}. If you have a lot of if-else statements these should probably be replaced by case statements, or redesign your code to use object oriented methods. If and while statements should be constructed of logic statements, no assignment or changing of data should occur.
Below is examples the syntax of the different PHP control structures. Notice the space after the control structure name, this is different from functions which does not have a space after the function name. PHP has different syntax rules for using control structures, the syntax below is preferred.
// if/else statement if ( $a == $b ) { ... } else { ... } // nested if/else statement if ( $a == $b ) { ... } else if ( $a == $c ) { ... } // while loop $i = 0; while ( $i < 100 ) { ... $i++; } // do..while loop $i = 0; do { ... $i++; } while ( $i < 100 ); // for loop for ( $i = 0; $i < 100; $i++ ) { ... } // foreach loop foreach ( $array as $value ) { ... } // switch switch ( $value ) { case 0: { ... }break; case 'text': { ... }break; default: { ... }break; }
Functions should be placed inside classes when possible. The syntax of functions are showed in the snipped below.
/*! This is my function. */ function &myFunction( $paramA = 1, $paramB = 2 ) { return 42; }
When indexing hash arrays you should use single quotes and no spaces.
$value = $myHashArray['IndexValue'];
All names should be English and grammatically correct. Names like "foo" and "tmp" should be avoided since they do not describe anything. Names should not contain numbers, numbers should be described with letters unless there is a good reason for it.
Example:
$ValueOne
Function names can be constructed of several words, all words should have lower-case except the first letter which should be an upper-case letter. The exception for this is the first letter which should always be in lower-case. If the first letter is part of an abbreviation the whole abbreviation should be in lower-case. Functions which return booleans should be named as a question (has, is, can ...).
Example:
setText(..); id(); setID(); getTheValuesForThis(); hasValue(); isValid(); canProcess();
Constants should be constructed by upper-case only letters, _ should be used to separate words.
Example:
define( 'MY_CONSTANT', 42 );
Member variables can be constructed of several words, every word is spelled in lower-case with a capital first letter. It should not be too many words, 1-3 is normal, they can be abbreviated as long as it's understandable.
Example:
$Len; $X, $Y; $FirstName;
Local variables can also consist of several words in lower-case, the first character of each word is a capital letter except the first word. The number of words should be as few as possible and the words can be abbreviated.
$index, $x, $y, i; $xAdd; $firstName, $lastName;
Parameters are names like local variables.
Class names can consist of several words, every word should be in lower-case with the first letter in capital. Classes should have a unique string which starts the name, for instance eZ, which is to uniquely identify the class.
Example:
eZUser eZContentObject eZImageVariation
Global variables are to be avoided, place them in a class and make them static.
POST variables should have the following syntax.
Class_FirstName Class_ValueOne Content_CategoryID Content_LongVariable SearchValue
The Class and Content names are called the base of the variable and should be used for variables which are specific for a certain module, function or page view. Variables such as SearchValue should be used for global values, all though you can also use Global as the base.
Global variables should be named uniquely by using the class name as the base of the name. For instance instance variables and global lists for classes.
$instance =& $GLOBALS['eZUserInstance']; $handlers =& $GLOBALS['eZCodecHandlers'];
All functions should be placed in classes unless there is a good reason not to.
Functions should be short and do one thing. The length of a function depends on the complexity of the function, the more complex the function is the shorter should the function be. If it gets too complex then divide the function up into helper functions.
The number of local variables in a function should not be larger than 7. 7 is a known limit to the number of things people can control at one time. Split up the function if it gets too large.
Default parameters should be used with care.
You should let the parameter line go over several lines with grouping of the similar parameters, if it gets long.
Classes should have one responsibility. All member variables are private. Helper functions should also be private. Functions that do not access member variables should be static.
The comments used should be written to comply with the syntax of the Doxygen tool. This tool, which is used to generate class reference documentation.
/*! \defgroup eZGroup Grouped classes Use groups to place common classes together. */ /*! \class eZMyClass ezmyclass.php \brief eZMyClass handles ... \ingroup eZGroup This is a more complete description of the class. Here is an code example: \code $myObj = new MyClass(); \endcode See also these classes: \sa eZUser, eZContentClass \todo Add this function.. \bug Does not handle... */ class MyClass { /*! This is the contructor of MyClass. It handles.... */ function MyClass() { ... } /*! \private This is a private helper function. */ function doSomething() { ... } /*! \return the value of ... */ function value() { } /*! \static This can be called like MyClass::doIt() */ function doIt() { ... } //// \privatesection /// This is a variable description. var $MyVar; }
When to use inline comments and when not to? These are some guidelines on what to do.
Inline comments are in general a means to explain what is going on in the code, however they have these problems.
Things which should be considered before writing inline comments.
In most cases the considerations above will help avoid inline comments. However in some cases they are required. Typical elements that require inline comments.
An inline comment alone is not always sufficient, sometimes it can be wise to also include the same or similar text in the API documentation. For instance to give information that it uses a workaround on a specific PHP version.
All inline comments should be written using end-of-line comments, like this.
// A workaround for PHP 4.2.2 were the xyz functionality is broken if ( php_version() == '4.2.2' ) { ... }
Comments
Re: Functions returning references
*- pike
Monday 30 October 2006 11:14:38 pm
I don't know, but I assume this:
some functions return variables with deep references, like $object1->attribute->object2. If you would retrieve $object2 through a different method afterwards, you want $object2 to refer to the same instance as $object1->attribute->object2. If you change an attribute in $object2, you want it to be changed in $object1->attribute->object2 as well.
if you don't specify you want a reference to the return value, php *may* make a deep copy of the returnvalue, after which you have 2 separate copies of $object2.
actually, I'm just guessing, but that would be a valid reason :-)
*-pike
Functions returning references
Harry Oosterveen
Thursday 06 October 2005 10:58:12 am
function &myFunction( $paramA = 1, $paramB = 2 )
Why is this? You might say, that this will improve performance, but the PHP manual is quite clear about it:
Returning by-reference is useful when you want to use a function to find which variable a reference should be bound to. Do not use return-by-reference to increase performance, the engine is smart enough to optimize this on its own. Only return references when you have a valid technical reason to do it!
(http://www.php.net/manual/en/language.references.return.php)