blob: fe7def12cf83874a95cc687c0e5d8fe4a4dbb998 [file] [log] [blame]
Derek Jones8ede1a22011-10-05 13:34:52 -05001########################
2General Style and Syntax
3########################
4
5The following page describes the use of coding rules adhered to when
6developing CodeIgniter.
7
8.. contents:: Table of Contents
9
10File Format
11===========
12
13Files should be saved with Unicode (UTF-8) encoding. The BOM should
14*not* be used. Unlike UTF-16 and UTF-32, there's no byte order to
15indicate in a UTF-8 encoded file, and the BOM can have a negative side
16effect in PHP of sending output, preventing the application from being
17able to set its own headers. Unix line endings should be used (LF).
18
19Here is how to apply these settings in some of the more common text
20editors. Instructions for your text editor may vary; check your text
21editor's documentation.
22
23TextMate
24''''''''
25
26#. Open the Application Preferences
27#. Click Advanced, and then the "Saving" tab
28#. In "File Encoding", select "UTF-8 (recommended)"
29#. In "Line Endings", select "LF (recommended)"
30#. *Optional:* Check "Use for existing files as well" if you wish to
31 modify the line endings of files you open to your new preference.
32
33BBEdit
34''''''
35
36#. Open the Application Preferences
37#. Select "Text Encodings" on the left.
38#. In "Default text encoding for new documents", select "Unicode (UTF-8,
39 no BOM)"
40#. *Optional:* In "If file's encoding can't be guessed, use", select
41 "Unicode (UTF-8, no BOM)"
42#. Select "Text Files" on the left.
43#. In "Default line breaks", select "Mac OS X and Unix (LF)"
44
45PHP Closing Tag
46===============
47
48The PHP closing tag on a PHP document **?>** is optional to the PHP
49parser. However, if used, any whitespace following the closing tag,
50whether introduced by the developer, user, or an FTP application, can
51cause unwanted output, PHP errors, or if the latter are suppressed,
52blank pages. For this reason, all PHP files should **OMIT** the closing
53PHP tag, and instead use a comment block to mark the end of file and
54it's location relative to the application root. This allows you to still
55identify a file as being complete and not truncated.
56
57::
58
59 INCORRECT: <?php echo "Here's my code!"; ?> CORRECT: <?php echo "Here's my code!"; /* End of file myfile.php */ /* Location: ./system/modules/mymodule/myfile.php */
60
61Class and Method Naming
62=======================
63
64Class names should always start with an uppercase letter. Multiple words
65should be separated with an underscore, and not CamelCased. All other
66class methods should be entirely lowercased and named to clearly
67indicate their function, preferably including a verb. Try to avoid
68overly long and verbose names.
69
70::
71
72 INCORRECT: class superclass class SuperClass CORRECT: class Super_class
73
74::
75
76 class Super_class { function __construct() { } }
77
78Examples of improper and proper method naming::
79
80 INCORRECT: function fileproperties() // not descriptive and needs underscore separator function fileProperties() // not descriptive and uses CamelCase function getfileproperties() // Better! But still missing underscore separator function getFileProperties() // uses CamelCase function get_the_file_properties_from_the_file() // wordy CORRECT: function get_file_properties() // descriptive, underscore separator, and all lowercase letters
81
82Variable Names
83==============
84
85The guidelines for variable naming is very similar to that used for
86class methods. Namely, variables should contain only lowercase letters,
87use underscore separators, and be reasonably named to indicate their
88purpose and contents. Very short, non-word variables should only be used
89as iterators in for() loops.
90
91::
92
93 INCORRECT: $j = 'foo'; // single letter variables should only be used in for() loops $Str // contains uppercase letters $bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning $groupid // multiple words, needs underscore separator $name_of_last_city_used // too long CORRECT: for ($j = 0; $j < 10; $j++) $str $buffer $group_id $last_city
94
95Commenting
96==========
97
98In general, code should be commented prolifically. It not only helps
99describe the flow and intent of the code for less experienced
100programmers, but can prove invaluable when returning to your own code
101months down the line. There is not a required format for comments, but
102the following are recommended.
103
104`DocBlock <http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html#basics.docblock>`_
105style comments preceding class and method declarations so they can be
106picked up by IDEs::
107
108 /** * Super Class * * @package Package Name * @subpackage Subpackage * @category Category * @author Author Name * @link http://example.com */ class Super_class {
109
110::
111
112 /** * Encodes string for use in XML * * @access public * @param string * @return string */ function xml_encode($str)
113
114Use single line comments within code, leaving a blank line between large
115comment blocks and code.
116
117::
118
119 // break up the string by newlines $parts = explode("\n", $str); // A longer comment that needs to give greater detail on what is // occurring and why can use multiple single-line comments. Try to // keep the width reasonable, around 70 characters is the easiest to // read. Don't hesitate to link to permanent external resources // that may provide greater detail: // // http://example.com/information_about_something/in_particular/ $parts = $this->foo($parts);
120
121Constants
122=========
123
124Constants follow the same guidelines as do variables, except constants
125should always be fully uppercase. *Always use CodeIgniter constants when
126appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc.*
127
128::
129
130 INCORRECT: myConstant // missing underscore separator and not fully uppercase N // no single-letter constants S_C_VER // not descriptive $str = str_replace('{foo}', 'bar', $str); // should use LD and RD constants CORRECT: MY_CONSTANT NEWLINE SUPER_CLASS_VERSION $str = str_replace(LD.'foo'.RD, 'bar', $str);
131
132TRUE, FALSE, and NULL
133=====================
134
135**TRUE**, **FALSE**, and **NULL** keywords should always be fully
136uppercase.
137
138::
139
140 INCORRECT: if ($foo == true) $bar = false; function foo($bar = null) CORRECT: if ($foo == TRUE) $bar = FALSE; function foo($bar = NULL)
141
142Logical Operators
143=================
144
145Use of **\|\|** is discouraged as its clarity on some output devices is
146low (looking like the number 11 for instance). **&&** is preferred over
147**AND** but either are acceptable, and a space should always precede and
148follow **!**.
149
150::
151
152 INCORRECT: if ($foo || $bar) if ($foo AND $bar) // okay but not recommended for common syntax highlighting applications if (!$foo) if (! is_array($foo)) CORRECT: if ($foo OR $bar) if ($foo && $bar) // recommended if ( ! $foo) if ( ! is_array($foo))
153
154Comparing Return Values and Typecasting
155=======================================
156
157Some PHP functions return FALSE on failure, but may also have a valid
158return value of "" or 0, which would evaluate to FALSE in loose
159comparisons. Be explicit by comparing the variable type when using these
160return values in conditionals to ensure the return value is indeed what
161you expect, and not a value that has an equivalent loose-type
162evaluation.
163
164Use the same stringency in returning and checking your own variables.
165Use **===** and **!==** as necessary.
166::
167
168 INCORRECT: // If 'foo' is at the beginning of the string, strpos will return a 0, // resulting in this conditional evaluating as TRUE if (strpos($str, 'foo') == FALSE) CORRECT: if (strpos($str, 'foo') === FALSE)
169
170::
171
172 INCORRECT: function build_string($str = "") { if ($str == "") // uh-oh! What if FALSE or the integer 0 is passed as an argument? { } } CORRECT: function build_string($str = "") { if ($str === "") { } }
173
174
175See also information regarding
176`typecasting <http://us3.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting>`_,
177which can be quite useful. Typecasting has a slightly different effect
178which may be desirable. When casting a variable as a string, for
179instance, NULL and boolean FALSE variables become empty strings, 0 (and
180other numbers) become strings of digits, and boolean TRUE becomes "1"::
181
182 $str = (string) $str; // cast $str as a string
183
184Debugging Code
185==============
186
187No debugging code can be left in place for submitted add-ons unless it
188is commented out, i.e. no var_dump(), print_r(), die(), and exit()
189calls that were used while creating the add-on, unless they are
190commented out.
191
192::
193
194 // print_r($foo);
195
196Whitespace in Files
197===================
198
199No whitespace can precede the opening PHP tag or follow the closing PHP
200tag. Output is buffered, so whitespace in your files can cause output to
201begin before CodeIgniter outputs its content, leading to errors and an
202inability for CodeIgniter to send proper headers. In the examples below,
203select the text with your mouse to reveal the incorrect whitespace.
204
205**INCORRECT**::
206
207 <?php // ...there is whitespace and a linebreak above the opening PHP tag // as well as whitespace after the closing PHP tag ?>
208
209**CORRECT**::
210
211 <?php // this sample has no whitespace before or after the opening and closing PHP tags ?>
212
213Compatibility
214=============
215
216Unless specifically mentioned in your add-on's documentation, all code
217must be compatible with PHP version 5.1+. Additionally, do not use PHP
218functions that require non-default libraries to be installed unless your
219code contains an alternative method when the function is not available,
220or you implicitly document that your add-on requires said PHP libraries.
221
222Class and File Names using Common Words
223=======================================
224
225When your class or filename is a common word, or might quite likely be
226identically named in another PHP script, provide a unique prefix to help
227prevent collision. Always realize that your end users may be running
228other add-ons or third party PHP scripts. Choose a prefix that is unique
229to your identity as a developer or company.
230
231::
232
233 INCORRECT: class Email pi.email.php class Xml ext.xml.php class Import mod.import.php CORRECT: class Pre_email pi.pre_email.php class Pre_xml ext.pre_xml.php class Pre_import mod.pre_import.php
234
235Database Table Names
236====================
237
238Any tables that your add-on might use must use the 'exp\_' prefix,
239followed by a prefix uniquely identifying you as the developer or
240company, and then a short descriptive table name. You do not need to be
241concerned about the database prefix being used on the user's
242installation, as CodeIgniter's database class will automatically convert
243'exp\_' to what is actually being used.
244
245::
246
247 INCORRECT: email_addresses // missing both prefixes pre_email_addresses // missing exp_ prefix exp_email_addresses // missing unique prefix CORRECT: exp_pre_email_addresses
248
249**NOTE:** Be mindful that MySQL has a limit of 64 characters for table
250names. This should not be an issue as table names that would exceed this
251would likely have unreasonable names. For instance, the following table
252name exceeds this limitation by one character. Silly, no?
253**exp_pre_email_addresses_of_registered_users_in_seattle_washington**
254One File per Class
255==================
256
257Use separate files for each class your add-on uses, unless the classes
258are *closely related*. An example of CodeIgniter files that contains
259multiple classes is the Database class file, which contains both the DB
260class and the DB_Cache class, and the Magpie plugin, which contains
261both the Magpie and Snoopy classes.
262
263Whitespace
264==========
265
266Use tabs for whitespace in your code, not spaces. This may seem like a
267small thing, but using tabs instead of whitespace allows the developer
268looking at your code to have indentation at levels that they prefer and
269customize in whatever application they use. And as a side benefit, it
270results in (slightly) more compact files, storing one tab character
271versus, say, four space characters.
272
273Line Breaks
274===========
275
276Files must be saved with Unix line breaks. This is more of an issue for
277developers who work in Windows, but in any case ensure that your text
278editor is setup to save files with Unix line breaks.
279
280Code Indenting
281==============
282
283Use Allman style indenting. With the exception of Class declarations,
284braces are always placed on a line by themselves, and indented at the
285same level as the control statement that "owns" them.
286
287::
288
289 INCORRECT: function foo($bar) { // ... } foreach ($arr as $key => $val) { // ... } if ($foo == $bar) { // ... } else { // ... } for ($i = 0; $i < 10; $i++) { for ($j = 0; $j < 10; $j++) { // ... } } CORRECT: function foo($bar) { // ... } foreach ($arr as $key => $val) { // ... } if ($foo == $bar) { // ... } else { // ... } for ($i = 0; $i < 10; $i++) { for ($j = 0; $j < 10; $j++) { // ... } }
290
291Bracket and Parenthetic Spacing
292===============================
293
294In general, parenthesis and brackets should not use any additional
295spaces. The exception is that a space should always follow PHP control
296structures that accept arguments with parenthesis (declare, do-while,
297elseif, for, foreach, if, switch, while), to help distinguish them from
298functions and increase readability.
299
300::
301
302 INCORRECT: $arr[ $foo ] = 'foo'; CORRECT: $arr[$foo] = 'foo'; // no spaces around array keys INCORRECT: function foo ( $bar ) { } CORRECT: function foo($bar) // no spaces around parenthesis in function declarations { } INCORRECT: foreach( $query->result() as $row ) CORRECT: foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis
303
304Localized Text
305==============
306
307Any text that is output in the control panel should use language
308variables in your lang file to allow localization.
309
310::
311
312 INCORRECT: return "Invalid Selection"; CORRECT: return $this->lang->line('invalid_selection');
313
314Private Methods and Variables
315=============================
316
317Methods and variables that are only accessed internally by your class,
318such as utility and helper functions that your public methods use for
319code abstraction, should be prefixed with an underscore.
320
321::
322
323 convert_text() // public method _convert_text() // private method
324
325PHP Errors
326==========
327
328Code must run error free and not rely on warnings and notices to be
329hidden to meet this requirement. For instance, never access a variable
330that you did not set yourself (such as $_POST array keys) without first
331checking to see that it isset().
332
333Make sure that while developing your add-on, error reporting is enabled
334for ALL users, and that display_errors is enabled in the PHP
335environment. You can check this setting with::
336
337 if (ini_get('display_errors') == 1) { exit "Enabled"; }
338
339On some servers where display_errors is disabled, and you do not have
340the ability to change this in the php.ini, you can often enable it with::
341
342 ini_set('display_errors', 1);
343
344**NOTE:** Setting the
345`display_errors <http://us.php.net/manual/en/ref.errorfunc.php#ini.display-errors>`_
346setting with ini_set() at runtime is not identical to having it enabled
347in the PHP environment. Namely, it will not have any effect if the
348script has fatal errors
349
350Short Open Tags
351===============
352
353Always use full PHP opening tags, in case a server does not have
354short_open_tag enabled.
355
356::
357
358 INCORRECT: <? echo $foo; ?> <?=$foo?> CORRECT: <?php echo $foo; ?>
359
360One Statement Per Line
361======================
362
363Never combine statements on one line.
364
365::
366
367 INCORRECT: $foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag); CORRECT: $foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag);
368
369Strings
370=======
371
372Always use single quoted strings unless you need variables parsed, and
373in cases where you do need variables parsed, use braces to prevent
374greedy token parsing. You may also use double-quoted strings if the
375string contains single quotes, so you do not have to use escape
376characters.
377
378::
379
380 INCORRECT: "My String" // no variable parsing, so no use for double quotes "My string $foo" // needs braces 'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly CORRECT: 'My String' "My string {$foo}" "SELECT foo FROM bar WHERE baz = 'bag'"
381
382SQL Queries
383===========
384
385MySQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE,
386AS, JOIN, ON, IN, etc.
387
388Break up long queries into multiple lines for legibility, preferably
389breaking for each clause.
390
391::
392
393 INCORRECT: // keywords are lowercase and query is too long for // a single line (... indicates continuation of line) $query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses ...where foo != 'oof' and baz != 'zab' order by foobaz limit 5, 100"); CORRECT: $query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz FROM exp_pre_email_addresses WHERE foo != 'oof' AND baz != 'zab' ORDER BY foobaz LIMIT 5, 100");
394
395Default Function Arguments
396==========================
397
398Whenever appropriate, provide function argument defaults, which helps
399prevent PHP errors with mistaken calls and provides common fallback
400values which can save a few lines of code. Example::
401
402 function foo($bar = '', $baz = FALSE)
403