Categories

  • No categories

Archives

Google

Google
Web www.barmala.com

Yahoo





PHP Style

» Web Authoring » Internet

 

 

Why

Style, for the most part, is about how to use whitespace (blank, tab, newline) to format source code and about how to name variables, functions and classes. Obviously this does not change the behavior of the program at all, but it may help others and sometimes even you in debugging and maintaining the code. You can imagine that there are many different views and sometimes even flame wars, about which format is more readable than another. However no matter, which style you prefer, keeping the same style throughout a whole project is obviously more readable than arbitrarily changing the style every few lines. Once you agreed that the style should stay consistent throughout a project, you'll probably agree too that it should even stay consistent within an organization. Instead of reinventing the wheel, i.e. inventing your own corporate style guide, it would be desirable that all projects use the same style, but that's exactly what does not happen.

are examples of two different style guides. That's bad for you as a programmer if you use both or if you even want to contribute to both.

Rather than proposing yet another style guide, the subsequent article points out some topics and proposals regarding style.

Indentation

Structured programming languages are often written in a style that shows the structure by indentation. But which character(s) do you use to indent? The most debated character is probably the tab (“\t”). Purists indent every level by a single tab, which equals 8 spaces in a fixed width font. This indentation becomes unpractical at higher indentation levels, which is why some editors set the tab width to 4 characters. Yet other editors indent by 4 spaces and combined 8 spaces into a single tab, which means that you indent by a mixture of tabs and spaces and a tab equals two indentation levels. This confusion is why yet other people and editors gave up completely about tabs and only use 2 or 4 spaces to indent. Since everyone is convince that his preferred indentation style is the only right one, most editors convert from foreign styles to their own. Needless to say, that this conversion does not always succeed. Some editor's behavior is configurable, but if you work for different projects with different style guides, you always have to reconfigure your editor. To save you from this work, vim provides the “modeline” feature, which allows you to set several editor options via a comment in your source. Pear shows an example of such a line.

Code Formatter

“Beautifiers” a.k.a. “Pretty Printers” like e.g. Beautify PHP are especially useful to automatically enforce a certain coding style. It's not a human who discretionary judges, which style is acceptable, but a machine, which is equally “fair” to everyone. This is especially useful if multiple people with different editors cooperate, and you want to make sure, that two versions in a version control system, e.g. CVS or Subversion, don't just differ by whitespace. You can run such a formatter during code check in.

Apropos version: Add the following line to the phpDocumentor block comment at the top of each page:

 * @version @(#) $Id: foo.php,v 1.0 2008/04/19 08:00:00 cvs Exp $

The version tag is followed by a tag for the what command. You may consider it deprecated, but it does not hurt. The rest between the “$” signs will be substituted by CVS (see for instance CVS Keywords).

Naming Conventions

The spelling of names for functions, classes, variables, ... is considered so important, that even terms for certain spellings exist, like e.g. $camelCase or $PascalCase. Maybe there is even a term for This_Case.

Yet other documents make statements about the grammar of these names. E.g. nouns should used for classes and variables, while verbs should be used for functions or methods. Therefore a function to display the header of a page shouldn't be called header(), but rather showHeader(). Constants, which enumerate possible values for a property, should use adjectives. Examples for such conventions are:

Documentation

Programmers consider all of their code self explanatory, so it does not need any type of documentation. You can even turn this argument around saying that a comment always shows a shortcoming of the language. A formal language at the right abstraction level can always describe a procedure more precisely than an informal language, and if a comment is needed to express what you intended, this proves that the language does not provide the means of expressing this.

Some Programmers even pretend that the source code was the best specification of a program, but if this was true, no program would ever have a bug, since every program behaves according to its specification.

Because team leaders know about the two arguments above and about the laziness of their team members, they try to educate programmers by requiring x comment lines per y code lines. “Smart” programmers escape this enforcement by writing useless comments like $i++; /* $i is incremented by one */, which is obvious to everyone, who knows this programming language. You may argue that a comment like /* next element in queue */ would be smarter, but wouldn't it be yet smarter then, to call the variable $QueueIndex instead and omit the comment?

The above examples (hopefully) show that comments should be abstract and therefore refer to code blocks rather than to single lines. So rather write /* do a quicksort on foo elements */ instead of commenting every single line.

This concept leads to the idea of basically just writing a single comment above each function or method and maybe above every global or member variable, but usually not commenting local vars and single code lines. Once you agree to this concept, you can even go a step further and replace your in-house style guide for comments by the manual of inline documenters like phpDocumentor, PHPXref or Doxygen. This has the advantage, that the documentation style can be partly enforced by a program rather than by a supervisor. And in addition you can automatically create a programmer's reference manual from the documentation. Of course this does not save you from writing a more descriptive manual, which explains the concepts.

If you have legacy code, which does not contain phpDocumentor comments, you may try to insert func_get_args and gettype statements after every function header and generate parameter names and type descriptions. This of course is only a semi automatic process. You have to add descriptions and convert traditional comments into the phpDocumentor syntax.

Miscellaneous

  • A PHP coding style, which is considered deprecated by some people, while still used by users is short open tags. A (non failsafe) attempt to change this, reads:
    find CodeDirectory -name "*.php" -exec sed -i -e 's/<?/<?php/g' -e 's/<?php=\(.*\)?>/<?php echo(\1); ?>/g' {} \;
  • An article about Common Style Mistakes
  • You may consider following OO paradigms like Patterns
  • You may prefer the traditional document type "HTML 4.01 Transitional", because more restricted types may conflict with elements imported from partner sites (advertising, banner exchange, ...). However the pages should actually try to follow "HTML 4.01 Strict" and in addition all tag names and attributes should be lower case and the attributes should be enclosed in double quotes in order to ensure forward compatibility with XHTML and simplify later migration to this standard.
  • To save you from issues with system, which don't handle non-ASCII characters correctly, you may fall back to the old fashioned "US-ASCII" and foreign languages have to use entity references like &uuml; or numeric references like &#number;. This might be quite tedious in Russian or in Asian languages, and it may significantly increase the file size, but it (hopefully) ensures maximum independence of the character set installed and won't be messed up if they are transferred between different platforms (Windows, DOS, Unix) or if someone edits the file with a dumb old editor.
  • Don't invent your own template engines, but rather consider an existing one like Smarty.