Coding

Overview

This section gives you an overview of FLOW3's coding rules and best practices.

General PHP best practices

  • All code should be object oriented. This means there should be no functions outside classes if not absolutely necessary. If you need a "container" for some helper methods, consider creating a static class.

  • All code must make use of PHP5 / PHP6 advanced features for object oriented programming.

  • Always use <?php as opening tags (never only <?)

  • Add an encoding declaration as the first line of your PHP code. For TYPO3 the encoding must be UTF-8

    Example 5.27. Encoding statement for .php files

    <?php
    declare(ENCODING = 'utf-8');
    
    ...


Comments

In general, comments are a good thing and we strive for creating a well-documented source code. However, inline comments can often be a sign for a bad code structure or method naming.[1]As an example, consider the following code:

Example 5.28. Bad coding smell: Comments

   // We only allow valid persons:
if (is_object($p) && strlen($p->lastN) > 0 && $p->hidden === FALSE && $this->environment->moonPhase === MOON_LIB::CRESCENT) {
   $xmM = $thd;
}



This is a perfect case for the refactoring technique "extract method": In order to avoid the comment, create a new method which is as explanatory as the comment:

Example 5.29. Smells better!

if ($this->isValidPerson($person) {
   $xmM = $thd;
}


Bottom line is: You may (and are encouraged to) use inline comments if they support the readability of your code. But always be aware of possible design flaws you probably try to hide with them.

Error handling and exceptions

FLOW3 makes use of a hierarchy for its exception classes. The general rule is to throw preferably specific exceptions and usually let them bubble up until a place where more general exceptions are catched. Consider the following example:

Some method tried to retrieve a component from the component manager. However, instead of providing a string containing the component name, the method passed an object (of course not on purpose - something went wrong). The component manager now throws an InvalidComponentNameException. In order to catch this exception you can, of course, catch it specifically - or only consider a more general ComponentException (or an even more general FLOW3Exception). This all works because we have the following hierarchy:

+ F3_FLOW3Exception
  + F3_FLOW3_ComponentException
    + F3_FLOW3_Component_InvalidComponentNameException

Cross platform issues




[1] This is also referred to as a bad "smell" in the theory of Refactoring. We highly recommend reading "Refactoring" by Martin Fowler - if you didn't already.