source: trunk/docs/coding_standards.txt @ 1

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

Initial import.

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