Strangecode coding standards 29 Aug 2005 20:12:49 ====================================================================== Preamble ====================================================================== Our standards follow closely the PEAR coding standards. Essential reading: http://pear.php.net/manual/en/standards.php ===================================================================== General guidelines ===================================================================== - Respect these coding styles. - Don't add npm dependencies if you can avoid it. If a new dependency is unavoidable, be mindful of its size, freshness and added value. - Use Svelte for all UI needs. - Try to not shoehorn your code into existing functions or components. - Simple is better. OOP is not inevitable. Simple functions often work as well, if not better. - If you must use OOP, avoid inheritance as much as possible, no one likes digging several layers of abstraction. - Comment the code. What, why, how, just make your intent clear. ====================================================================== File Naming Conventions ====================================================================== script.php Public accessible scripts. Auth_SQL.inc.php One PHP Class to be included. The filename is the type of class, underscore, name. Or if in subdirs, this could be /Auth/SQL.inc.php while the class name remains "Auth_SQL" some_file.inc.html HTML file, which may or may not have some PHP, but will be included by some other PHP file. Never includes sensitive code as these files may be accessed directly in the web root. script.cli.php A command-line executable script, possibly executed with CRON. Outputs TEXT if any instead of HTML. script.inc.eml Text file to be sent by email. schema.mysql Database schema file that goes with the application. main.screen.css CSS file with media: screen/print/all main.print.css ====================================================================== Indenting and Wrap ====================================================================== Use an indent of 4 spaces, with no tabs. Code and especially comments should usually be wrapped <= 80 characters. Exceptions are made in the case where code readability is significantly improved with longer lines. ====================================================================== Control Structures ====================================================================== These include if, for, while, switch, etc. Here is an example if statement, since it is the most complicated of them: if ((condition1) || (condition2)) { action1; } else if ((condition3) && (condition4)) { action2; } else { defaultaction; } Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls. Even in the case of an if with no else clauses, and only a 1 line action, the curly braces should still be used: if (condition) { action; } This improves readability and allows easy extension of the clause. For switch statements: switch (condition) { case 1: action1; break; case 2: action2; break; default: defaultaction; break; } ====================================================================== Function Calls ====================================================================== Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example: $var = foo($bar, $baz, $quux); As displayed above, there should be one space on either side of an equals sign used to assign the return value of a function to a variable. In the case of a block of related assignments, more space may be inserted to promote readability: $short = foo($bar); $long_variable = foo($baz); ====================================================================== Function and Method Definitions ====================================================================== Function declaractions follow the "one true brace" convention: function fooFunction($arg1, $arg2 = '') { if (condition) { statement; } return $val; } Arguments with default values go at the end of the argument list. Always attempt to return a meaningful value from a function if one is appropriate. Use lowerCamelCase for function and method names to distinguish from php internal functions which standard on underscore_space_style_names(). ====================================================================== Return Values ====================================================================== When functions return boolean values, use 'return false;' or 'return true;' as opposed to 'return 0;' or 'return 1;' or 'return(-1);', except when boolean plurality is necessary. ====================================================================== String Concatenation ====================================================================== Always include a space before and after the concatenation operator '.' which improves readability and improves search-and-replace of adjacent elements. $something = $blah . funky() . ".\".=" . $blab; is better than: $something = $blah.funky().".\".=".$blab; ====================================================================== Quote Marks ====================================================================== Use the single quote marks ' to enclose simple strings whenever possible. Double quote marks " require extra parsing and thus slow things down, but are necessary if entities there must be swapped-out such as variables or control characters. $var['singlequote'] = 'singlequote'; $var["doublequote-$i"] = "$vars and \n funny \t %s things need doublequotes"; $var['doublequote-' . $i] = $var . 'you can do this' . "\t %s" . $var2 . 'but it isn\'t any better'; ====================================================================== Printing HTML ====================================================================== For large or complex blocks of HTML, using the following method is much faster and safer than echo because the php processor is bypassed and content goes directly to output:
Contact us

Just a single-line of html

====================================================================== Comments ====================================================================== Function comments should follow the Javadoc standard, with detailed function comments and one-line pointers along the way: http://java.sun.com/products/jdk/javadoc/writingdoccomments/index.html Here is an example of the codebase method Email::validEmail(): * @since 30 Nov 2005 22:00:50 */ function validEmail($email) { $app =& App::getInstance(); // If an array, check values recursively. if (is_array($email)) { foreach ($email as $e) { if (!$this->validEmail($e)) { return false; } } return true; } else { // To be valid email address must match regex and fit within the length constraints. if (preg_match($this->getParam('regex'), $email, $e_parts) && mb_strlen($e_parts[2]) < 64 && mb_strlen($e_parts[3]) < 255) { return true; } else { $app->logMsg(sprintf('Invalid email: %s', $email), LOG_INFO, __FILE__, __LINE__); return false; } } } ?> Single line comments should be of the double-slash variety, and be on the line above the code being commented upon: ====================================================================== Including Code ====================================================================== If you are including a class, function library, or anything else which would cause a parse error if included twice, always use include_once. This will ensure that no matter how many factory methods we use or how much dynamic inclusion we do, the library will only be included once. If you are including a static filename, such as a conf file or a template that is _always_ used, use require. If you are dynamically including a filename, or want the code to only be used conditionally (an optional template), use include. ====================================================================== PHP Code Tags ====================================================================== Always use to delimit PHP code, not the shorthand. Even use instead of . ====================================================================== php.ini Settings ====================================================================== All code should work with register_globals = Off. This means using $_REQUEST, $_GET, $_POST, $_COOKIE, $_SESSION, $_SERVER, and $_ENV to access all request, get, post, cookie, session, server, and environment data, respectively. All code should work with error_reporting = E_ALL. Failure to do so would result in ugly output, error logs getting filled with lots of warning messages, or even downright broken scripts. All code should work regardless of the setting of magic_quotes_gpc. Form data should be passed through stripslashes() if necessary. No code should assume that '.' is in the include path. Always specify './' in front of a filename when you are including a file in the same directory. Or better yet, for less abiguity, use: include dirname(__FILE__) . '/include_me.inc.php'; ====================================================================== XHTML 1.0 Compliance ====================================================================== All HTML should be valid XHTML 1.0 verified with the W3C Markup Validation Service: http://validator.w3.org/ All tag names and parameters must be lower case including javascript event handlers:
...
... All tag parameters must be of a valid parameter="value" form (numeric values must also be surrounded by quotes). For parameters that had no value in HTML, the parameter name is the value. For example: Example All tags must be properly closed. Tags without a closing part must follow the XHTML convention and end with a space and a slash:

Example All form definitions must be on their own line and either fully defined within a pair or be outside table tags. Forms must also always have an action parameter:
example
All JavaScript tags must have a valid language and type parameters: Nothing may appear after , therefore include any common footers after all other output. All images must have an alt parameter: <?php echo _(" /> Input field of type "image" does not allow the border parameter, and may render with a border on some browsers. Use the following instead: <?php echo _(" /> ====================================================================== Database Naming Conventions ====================================================================== All database tables need to make sure that their table and field names work in all databases. Many databases reserve words like 'uid', 'user', etc. for internal use, and forbid words that are SQL keywords (select, where, etc.). Adding '_tbl' to the end of the table name is a good idea for this reason and also improves searching for the table names in the code. A good way to do this for field names is to make the field name table_name_field_name. When building queries referencing two-or-more tables always preface columns with the table containing the column (admin_tbl.username, location_tbl.location_address). This method is much preferred over using aliases of table names (a.username, l.location_address). Table names should be singular (user_tbl instead of users_tbl).