source: branches/1.1dev/docs/coding_standards.txt

Last change on this file was 1, checked in by scdev, 19 years ago

Initial import.

File size: 12.5 KB
Line 
1Strangecode internal coding standards
2www.strangecode.com
3updated 2004-10-24
4
5
6======================================================================
7File naming conventions
8======================================================================
9
10script.php              Public accessible scripts.
11
12
13my_lib_file.inc.php     PHP library to be included by script. Contains no (or small amount of) HTML
14
15FormValidator.inc.php   One PHP Class to be included, no HTML. The name of the
16                        class is the first part of the filename.
17
18some_file.ihtml         HTML file, which may or may not include PHP,
19                        but will be included by some other PHP file. Never
20                        includes sensitive code as these files may be accessed
21                        directly in the web root.
22
23script.cli.php          A command-line executable script, possibly executed
24                        with CRON, usually outputs TEXT, not HTML.
25
26dbname.mysql            Database schema file that goes with the application.
27
28main.screen.css         CSS file with media: screen/print/all
29main.print.css
30
31
32======================================================================
33Indenting and wrap
34======================================================================
35
36Use an indent of 4 spaces, with no tabs. Code and especially comments should
37be wrapped <= 80 characters. Exceptions are made in the case where code
38readability is significantly improved with longer lines.
39
40
41======================================================================
42Control Structures
43======================================================================
44
45These include if, for, while, switch, etc. Here is an example if statement,
46since it is the most complicated of them:
47
48    if ((condition1) || (condition2)) {
49        action1;
50    } else if ((condition3) && (condition4)) {
51        action2;
52    } else {
53        defaultaction;
54    }
55
56Control statements should have one space between the control keyword
57and opening parenthesis, to distinguish them from function calls.
58
59Even in the case of an if with no else clauses, and only a 1 line action,
60the curly braces should still be used:
61
62    if (condition) {
63        action;
64    }
65
66This improves readability and allows easy extension of the clause.
67
68For switch statements:
69
70    switch (condition) {
71    case 1:
72        action1;
73        break;
74   
75    case 2:
76        action2;
77        break;
78   
79    default:
80        defaultaction;
81        break;
82   
83    }
84
85
86======================================================================
87Function Calls
88======================================================================
89
90Functions should be called with no spaces between the function name,
91the opening parenthesis, and the first parameter; spaces between commas
92and each parameter, and no space between the last parameter, the
93closing parenthesis, and the semicolon. Here's an example:
94
95    $var = foo($bar, $baz, $quux);
96
97As displayed above, there should be one space on either side of an
98equals sign used to assign the return value of a function to a
99variable. In the case of a block of related assignments, more space
100may be inserted to promote readability:
101
102    $short         = foo($bar);
103    $long_variable = foo($baz);
104
105
106======================================================================
107Function Definitions
108======================================================================
109
110Function declaractions follow the "one true brace" convention:
111
112    function fooFunction($arg1, $arg2 = '')
113    {
114        if (condition) {
115            statement;
116        }
117        return $val;
118    }
119
120Arguments with default values go at the end of the argument list. Always
121attempt to return a meaningful value from a function if one is appropriate.
122
123Recommend using studlyCaps for function names, to distinguish from php
124internal functions which standard on under_score_space() style names.
125
126
127======================================================================
128Return values
129======================================================================
130
131When functions return boolean values, use 'return false;' or 'return true;'
132as opposed to 'return 0;' or 'return 1;' or 'return(-1);'.
133
134
135======================================================================
136String concatination
137======================================================================
138
139Always include a space before and after the concatonation operator '.' which
140improves readability and improves search-and-replace of adjacent elements.
141
142    $something = $blah . funky() . ".\".=" . $blab;
143   
144is better than:
145   
146    $something = $blah.funky().".\".=".$blab;
147
148
149======================================================================
150Quote marks
151======================================================================
152
153Use the single quote marks ' to enclose simple strings whenever possible.
154Double quote marks " require extra parsing and thus slow things down, but
155are necessary if entities there must be swapped-out such as variables or
156control characters.
157
158        $var['singlequote'] = 'singlequote';
159        $var["doublequote-$i"] = "$vars and \n funny \t %s things need doublequotes";
160        $var['doublequote-' . $i] = $var . 'you can do this' . "\t %s" . $var2 .
161        'but it isn\'t any better';
162
163
164======================================================================
165Printing html
166======================================================================
167
168For large or complex blocks of HTML, using the following method is much faster
169and safer than echo because the php processesor is bypassed and content goes
170directly to output:
171
172    <?php
173    if (something) {
174        // Here comes the HTML...
175        ?>
176        <div align="right" class="tiny">
177        [&nbsp;<a href="<?php echo ohref('contact.php') ?>">Contact us</a>&nbsp;]
178        </div>
179        <?php
180    } else if (somethingelse) {
181        ?><h1>Just a little html</h1><?php
182    }
183    ?>
184
185
186======================================================================
187Comments
188======================================================================
189
190Function comments should follow the Javadoc standard, with detailed
191function comments and one-line pointers along the way:
192http://java.sun.com/products/jdk/javadoc/writingdoccomments/index.html
193 
194    <?php
195    /**
196     * Description of function.
197     *
198     * @access  public
199     * @param   string  $db_table   Database table.
200     * @param   string  $db_column  Database column containing set or enum datatype.
201     * @return  array               The set/enum values or false on failure.
202     * @author  Quinn Comendant <quinn@strangecode.com>
203     * @version 1.0
204     * @since   24 Feb 2004 19:34:04
205     */
206    function getSetEnumFieldValues()
207    {
208        $qid = dbQuery("SHOW COLUMNS FROM $db_table LIKE '$db_col'",false);
209           
210        $row = mysql_fetch_row($qid);
211        if (preg_match('/^enum|^set/i', $row[1]) && preg_match_all("/'([^']*)'/", $row[1], $match)) {
212            return $match[1];
213        } else {
214            return false;
215        }
216    }
217    ?>
218
219Single line comments should be of the double-slash variety, and be on the line above the
220code being commented upon:
221
222    <?php
223    // If the last word in $var is peanuts, set $need_peanuts to TRUE.
224    $need_peanuts = preg_match('/peanuts$/i', $var);
225    ?>
226
227
228======================================================================
229Including Code
230======================================================================
231
232If you are including a class, function library, or anything else which would
233cause a parse error if included twice, always use include_once. This will
234ensure that no matter how many factory methods we use or how much dynamic
235inclusion we do, the library will only be included once.
236
237If you are including a static filename, such as a conf file or a template
238that is _always_ used, use require.
239
240If you are dynamically including a filename, or want the code to only be
241used conditionally (an optional template), use include.
242
243
244======================================================================
245PHP Code Tags
246======================================================================
247
248ALWAYS use <?php ?> to delimit PHP code, not the <?php ?> shorthand. Even
249use <?php echo $name ?> instead of <?php echo $name; ?>.
250
251
252======================================================================
253php.ini settings
254======================================================================
255
256All code should work with register_globals = Off. This means using
257$_GET, $_POST, $_COOKIE, $_SESSION,
258$_SERVER, and $_ENV to access all get, post, cookie,
259session, server, and environment data, respectively.
260
261All code should work with error_reporting = E_ALL. Failure to do so would
262result in ugly output, error logs getting filled with lots of warning messages,
263or even downright broken scripts.
264
265All code should work regardless of the setting of magic_quotes_gpc.
266Form data should be passed through stripslashes if necessary.
267
268No code should assume that '.' is in the include path. Always
269specify './' in front of a filename when you are including a file in
270the same directory.
271
272
273======================================================================
274XHTML 1.0 Compliance
275======================================================================
276
277All HTML should be valid XHTML 1.0 verfied with the
278W3C Markup Validation Service: http://validator.w3.org/
279
280All tag names and parameters must be lower case including javascript
281event handlers:
282
283    <div class="mofogo">...</div>
284    <a href="http://www.example.com/" onmouseover="status=''" onmouseout="status=''">...</a>
285
286All tag parameters must be of a valid parameter="value" form (numeric
287values must also be surrounded by quotes).  For parameters that had no
288value in HTML, the parameter name is the value.  For example:
289
290    <input type="checkbox" checked="checked">
291    <select name="example">
292        <option selected="selected" value="1">Example</option>
293    </select>
294    <td nowrap="nowrap">Example</td>
295
296All tags must be properly closed. Tags without a closing part must follow the
297XHTML convention and end with a space and a slash:
298
299    <br />
300    <hr />
301    <img src="example.gif" alt="Example" />
302    <input type="submit" value="Example" />
303
304All form definitions must be on their own line and either fully defined within
305a <td></td> pair or be outside table tags. Forms must also aways have an action
306parameter:
307
308    <form method="post" action="http://example.com/example.cgi">
309    <table>
310        <tr><td>example</td></tr>
311    </table>
312    </from>
313
314    <table>
315        <tr><td>
316            <form action="javascript:void(0)" onsubmit="return false;">
317            </form>
318        </td></tr>
319    </table>
320
321All JavaScript tags must have a valid language and type parameters:
322
323    <script language="JavaScript" type="text/javascript">
324    <!--
325    ...
326    // -->
327    </script>
328
329Nothing may appear after </html>, therefore include any common footers after
330all other output.
331
332All images must have an alt parameter:
333
334    <img src="example.gif" alt="<?php echo _("Example"); ?>" />
335
336Input field of type "image" does not allow the border parameter, and may render
337with a border on some browsers.  Use the following instead:
338
339   <a href="" onclick="document.formname.submit(); return false;"><img src="example.gif" alt="<?php echo _("Example"); ?>" /></a>
340
341
342======================================================================
343Database Naming Conventions
344======================================================================
345
346All database tables need to make sure that their table and field names work in all
347databases. Many databases reserve words like 'uid', 'user', etc. for
348internal use, and forbid words that are SQL keywords (select, where,
349etc.). Adding '_tbl' to the end of the table name is a good idea for this reason
350and also improves searching for the table names in the code.
351
352A good way to do this for field names is to make the field name
353table_name_field_name.
354
355When building queries referencing two-or-more tables always preface columns
356with the table containing the column (admin_tbl.username, location_tbl.location_address).
357This method is much prefered over using aliases of table names (a.username, l.location_address).
358
359Table names should be singular (user_tbl instead of users_tbl).
360
361
362======================================================================
363Regular Expression Use
364======================================================================
365
366Always use the preg_* functions if possible instead of ereg_* (and
367preg_split() instead of split()); they are included in PHP by default
368and much more efficient and much faster than ereg_*.
369
370NEVER use a regular expression to match or replace a static string.
371Use explode() (in place of split()), str_replace(), strstr(), or strtr()
372which does the job much more efficiently.
Note: See TracBrowser for help on using the repository browser.