blob: 0373fc79131c273a67ec2e9d86abf79d683bf544 [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
Derek Jones129c1812011-10-05 17:15:44 -050057**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -050058
Derek Jones129c1812011-10-05 17:15:44 -050059 <?php
60
61 echo "Here's my code!";
62
63 ?>
64
65**CORRECT**::
66
67 <?php
68
69 echo "Here's my code!";
70
71 /* End of file myfile.php */
72 /* Location: ./system/modules/mymodule/myfile.php */
Derek Jones8ede1a22011-10-05 13:34:52 -050073
74Class and Method Naming
75=======================
76
77Class names should always start with an uppercase letter. Multiple words
78should be separated with an underscore, and not CamelCased. All other
79class methods should be entirely lowercased and named to clearly
80indicate their function, preferably including a verb. Try to avoid
81overly long and verbose names.
82
Derek Jones129c1812011-10-05 17:15:44 -050083**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -050084
Derek Jones129c1812011-10-05 17:15:44 -050085 class superclass
86 class SuperClass
87
88**CORRECT**::
89
90 class Super_class
Derek Jones8ede1a22011-10-05 13:34:52 -050091
92::
93
Derek Jones129c1812011-10-05 17:15:44 -050094 class Super_class {
Derek Jones8ede1a22011-10-05 13:34:52 -050095
Derek Jones129c1812011-10-05 17:15:44 -050096 function __construct()
97 {
Derek Jones8ede1a22011-10-05 13:34:52 -050098
Derek Jones129c1812011-10-05 17:15:44 -050099 }
100 }
101
102Examples of improper and proper method naming:
103
104**INCORRECT**::
105
106 function fileproperties() // not descriptive and needs underscore separator
107 function fileProperties() // not descriptive and uses CamelCase
108 function getfileproperties() // Better! But still missing underscore separator
109 function getFileProperties() // uses CamelCase
110 function get_the_file_properties_from_the_file() // wordy
111
112**CORRECT**::
113
114 function get_file_properties() // descriptive, underscore separator, and all lowercase letters
Derek Jones8ede1a22011-10-05 13:34:52 -0500115
116Variable Names
117==============
118
119The guidelines for variable naming is very similar to that used for
120class methods. Namely, variables should contain only lowercase letters,
121use underscore separators, and be reasonably named to indicate their
122purpose and contents. Very short, non-word variables should only be used
123as iterators in for() loops.
124
Derek Jones129c1812011-10-05 17:15:44 -0500125**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500126
Derek Jones129c1812011-10-05 17:15:44 -0500127 $j = 'foo'; // single letter variables should only be used in for() loops
128 $Str // contains uppercase letters
129 $bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning
130 $groupid // multiple words, needs underscore separator
131 $name_of_last_city_used // too long
132
133**CORRECT**::
134
135 for ($j = 0; $j < 10; $j++)
136 $str
137 $buffer
138 $group_id
139 $last_city
Derek Jones8ede1a22011-10-05 13:34:52 -0500140
141Commenting
142==========
143
144In general, code should be commented prolifically. It not only helps
145describe the flow and intent of the code for less experienced
146programmers, but can prove invaluable when returning to your own code
147months down the line. There is not a required format for comments, but
148the following are recommended.
149
150`DocBlock <http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html#basics.docblock>`_
151style comments preceding class and method declarations so they can be
152picked up by IDEs::
153
Derek Jones129c1812011-10-05 17:15:44 -0500154 /**
155 * Super Class
156 *
157 * @package Package Name
158 * @subpackage Subpackage
159 * @category Category
160 * @author Author Name
161 * @link http://example.com
162 */
163 class Super_class {
Derek Jones8ede1a22011-10-05 13:34:52 -0500164
165::
166
Derek Jones129c1812011-10-05 17:15:44 -0500167 /**
168 * Encodes string for use in XML
169 *
170 * @access public
171 * @param string
172 * @return string
173 */
174 function xml_encode($str)
Derek Jones8ede1a22011-10-05 13:34:52 -0500175
176Use single line comments within code, leaving a blank line between large
177comment blocks and code.
178
179::
180
Derek Jones129c1812011-10-05 17:15:44 -0500181 // break up the string by newlines
182 $parts = explode("\n", $str);
183
184 // A longer comment that needs to give greater detail on what is
185 // occurring and why can use multiple single-line comments. Try to
186 // keep the width reasonable, around 70 characters is the easiest to
187 // read. Don't hesitate to link to permanent external resources
188 // that may provide greater detail:
189 //
190 // http://example.com/information_about_something/in_particular/
191
192 $parts = $this->foo($parts);
Derek Jones8ede1a22011-10-05 13:34:52 -0500193
194Constants
195=========
196
197Constants follow the same guidelines as do variables, except constants
198should always be fully uppercase. *Always use CodeIgniter constants when
199appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc.*
200
Derek Jones129c1812011-10-05 17:15:44 -0500201**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500202
Derek Jones129c1812011-10-05 17:15:44 -0500203 myConstant // missing underscore separator and not fully uppercase
204 N // no single-letter constants
205 S_C_VER // not descriptive
206 $str = str_replace('{foo}', 'bar', $str); // should use LD and RD constants
207
208**CORRECT**::
209
210 MY_CONSTANT
211 NEWLINE
212 SUPER_CLASS_VERSION
213 $str = str_replace(LD.'foo'.RD, 'bar', $str);
Derek Jones8ede1a22011-10-05 13:34:52 -0500214
215TRUE, FALSE, and NULL
216=====================
217
218**TRUE**, **FALSE**, and **NULL** keywords should always be fully
219uppercase.
220
Derek Jones129c1812011-10-05 17:15:44 -0500221**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500222
Derek Jones129c1812011-10-05 17:15:44 -0500223 if ($foo == true)
224 $bar = false;
225 function foo($bar = null)
226
227**CORRECT**::
228
229 if ($foo == TRUE)
230 $bar = FALSE;
231 function foo($bar = NULL)
Derek Jones8ede1a22011-10-05 13:34:52 -0500232
233Logical Operators
234=================
235
236Use of **\|\|** is discouraged as its clarity on some output devices is
237low (looking like the number 11 for instance). **&&** is preferred over
238**AND** but either are acceptable, and a space should always precede and
239follow **!**.
240
Derek Jones129c1812011-10-05 17:15:44 -0500241**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500242
Derek Jones129c1812011-10-05 17:15:44 -0500243 if ($foo || $bar)
244 if ($foo AND $bar) // okay but not recommended for common syntax highlighting applications
245 if (!$foo)
246 if (! is_array($foo))
247
248**CORRECT**::
249
250 if ($foo OR $bar)
251 if ($foo && $bar) // recommended
252 if ( ! $foo)
253 if ( ! is_array($foo))
254
Derek Jones8ede1a22011-10-05 13:34:52 -0500255
256Comparing Return Values and Typecasting
257=======================================
258
259Some PHP functions return FALSE on failure, but may also have a valid
260return value of "" or 0, which would evaluate to FALSE in loose
261comparisons. Be explicit by comparing the variable type when using these
262return values in conditionals to ensure the return value is indeed what
263you expect, and not a value that has an equivalent loose-type
264evaluation.
265
266Use the same stringency in returning and checking your own variables.
267Use **===** and **!==** as necessary.
Derek Jones8ede1a22011-10-05 13:34:52 -0500268
Derek Jones129c1812011-10-05 17:15:44 -0500269**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500270
Derek Jones129c1812011-10-05 17:15:44 -0500271 // If 'foo' is at the beginning of the string, strpos will return a 0,
272 // resulting in this conditional evaluating as TRUE
273 if (strpos($str, 'foo') == FALSE)
Derek Jones8ede1a22011-10-05 13:34:52 -0500274
Derek Jones129c1812011-10-05 17:15:44 -0500275**CORRECT**::
276
277 if (strpos($str, 'foo') === FALSE)
278
279**INCORRECT**::
280
281 function build_string($str = "")
282 {
283 if ($str == "") // uh-oh! What if FALSE or the integer 0 is passed as an argument?
284 {
285
286 }
287 }
288
289**CORRECT**::
290
291 function build_string($str = "")
292 {
293 if ($str === "")
294 {
295
296 }
297 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500298
299
300See also information regarding
301`typecasting <http://us3.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting>`_,
302which can be quite useful. Typecasting has a slightly different effect
303which may be desirable. When casting a variable as a string, for
304instance, NULL and boolean FALSE variables become empty strings, 0 (and
305other numbers) become strings of digits, and boolean TRUE becomes "1"::
306
307 $str = (string) $str; // cast $str as a string
308
309Debugging Code
310==============
311
312No debugging code can be left in place for submitted add-ons unless it
313is commented out, i.e. no var_dump(), print_r(), die(), and exit()
314calls that were used while creating the add-on, unless they are
315commented out.
316
317::
318
319 // print_r($foo);
320
321Whitespace in Files
322===================
323
324No whitespace can precede the opening PHP tag or follow the closing PHP
325tag. Output is buffered, so whitespace in your files can cause output to
326begin before CodeIgniter outputs its content, leading to errors and an
327inability for CodeIgniter to send proper headers. In the examples below,
328select the text with your mouse to reveal the incorrect whitespace.
329
Derek Jones8ede1a22011-10-05 13:34:52 -0500330
331Compatibility
332=============
333
334Unless specifically mentioned in your add-on's documentation, all code
335must be compatible with PHP version 5.1+. Additionally, do not use PHP
336functions that require non-default libraries to be installed unless your
337code contains an alternative method when the function is not available,
338or you implicitly document that your add-on requires said PHP libraries.
339
340Class and File Names using Common Words
341=======================================
342
343When your class or filename is a common word, or might quite likely be
344identically named in another PHP script, provide a unique prefix to help
345prevent collision. Always realize that your end users may be running
346other add-ons or third party PHP scripts. Choose a prefix that is unique
347to your identity as a developer or company.
348
Derek Jones129c1812011-10-05 17:15:44 -0500349**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500350
Derek Jones129c1812011-10-05 17:15:44 -0500351 class Email pi.email.php
352 class Xml ext.xml.php
353 class Import mod.import.php
354
355**CORRECT**::
356
357 class Pre_email pi.pre_email.php
358 class Pre_xml ext.pre_xml.php
359 class Pre_import mod.pre_import.php
Derek Jones8ede1a22011-10-05 13:34:52 -0500360
361Database Table Names
362====================
363
364Any tables that your add-on might use must use the 'exp\_' prefix,
365followed by a prefix uniquely identifying you as the developer or
366company, and then a short descriptive table name. You do not need to be
367concerned about the database prefix being used on the user's
368installation, as CodeIgniter's database class will automatically convert
369'exp\_' to what is actually being used.
370
Derek Jones129c1812011-10-05 17:15:44 -0500371**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500372
Derek Jones129c1812011-10-05 17:15:44 -0500373 email_addresses // missing both prefixes
374 pre_email_addresses // missing exp_ prefix
375 exp_email_addresses // missing unique prefix
Derek Jones8ede1a22011-10-05 13:34:52 -0500376
Derek Jones129c1812011-10-05 17:15:44 -0500377**CORRECT**::
378
379 exp_pre_email_addresses
380
381.. note:: Be mindful that MySQL has a limit of 64 characters for table
382 names. This should not be an issue as table names that would exceed this
383 would likely have unreasonable names. For instance, the following table
384 name exceeds this limitation by one character. Silly, no?
385 **exp_pre_email_addresses_of_registered_users_in_seattle_washington**
386
Derek Jones8ede1a22011-10-05 13:34:52 -0500387One File per Class
388==================
389
390Use separate files for each class your add-on uses, unless the classes
391are *closely related*. An example of CodeIgniter files that contains
392multiple classes is the Database class file, which contains both the DB
393class and the DB_Cache class, and the Magpie plugin, which contains
394both the Magpie and Snoopy classes.
395
396Whitespace
397==========
398
399Use tabs for whitespace in your code, not spaces. This may seem like a
400small thing, but using tabs instead of whitespace allows the developer
401looking at your code to have indentation at levels that they prefer and
402customize in whatever application they use. And as a side benefit, it
403results in (slightly) more compact files, storing one tab character
404versus, say, four space characters.
405
406Line Breaks
407===========
408
409Files must be saved with Unix line breaks. This is more of an issue for
410developers who work in Windows, but in any case ensure that your text
411editor is setup to save files with Unix line breaks.
412
413Code Indenting
414==============
415
416Use Allman style indenting. With the exception of Class declarations,
417braces are always placed on a line by themselves, and indented at the
418same level as the control statement that "owns" them.
419
Derek Jones129c1812011-10-05 17:15:44 -0500420**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500421
Derek Jones129c1812011-10-05 17:15:44 -0500422 function foo($bar) {
423 // ...
424 }
425
426 foreach ($arr as $key => $val) {
427 // ...
428 }
429
430 if ($foo == $bar) {
431 // ...
432 } else {
433 // ...
434 }
435
436 for ($i = 0; $i < 10; $i++)
437 {
438 for ($j = 0; $j < 10; $j++)
439 {
440 // ...
441 }
442 }
443
444**CORRECT**::
445
446 function foo($bar)
447 {
448 // ...
449 }
450
451 foreach ($arr as $key => $val)
452 {
453 // ...
454 }
455
456 if ($foo == $bar)
457 {
458 // ...
459 }
460 else
461 {
462 // ...
463 }
464
465 for ($i = 0; $i < 10; $i++)
466 {
467 for ($j = 0; $j < 10; $j++)
468 {
469 // ...
470 }
471 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500472
473Bracket and Parenthetic Spacing
474===============================
475
476In general, parenthesis and brackets should not use any additional
477spaces. The exception is that a space should always follow PHP control
478structures that accept arguments with parenthesis (declare, do-while,
479elseif, for, foreach, if, switch, while), to help distinguish them from
480functions and increase readability.
481
Derek Jones129c1812011-10-05 17:15:44 -0500482**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500483
Derek Jones129c1812011-10-05 17:15:44 -0500484 $arr[ $foo ] = 'foo';
485
486**CORRECT**::
487
488 $arr[$foo] = 'foo'; // no spaces around array keys
489
490**INCORRECT**::
491
492 function foo ( $bar )
493 {
494
495 }
496
497**CORRECT**::
498
499 function foo($bar) // no spaces around parenthesis in function declarations
500 {
501
502 }
503
504**INCORRECT**::
505
506 foreach( $query->result() as $row )
507
508**CORRECT**::
509
510 foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis
Derek Jones8ede1a22011-10-05 13:34:52 -0500511
512Localized Text
513==============
514
515Any text that is output in the control panel should use language
516variables in your lang file to allow localization.
517
Derek Jones129c1812011-10-05 17:15:44 -0500518**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500519
Derek Jones129c1812011-10-05 17:15:44 -0500520 return "Invalid Selection";
521
522**CORRECT**::
523
524 return $this->lang->line('invalid_selection');
Derek Jones8ede1a22011-10-05 13:34:52 -0500525
526Private Methods and Variables
527=============================
528
529Methods and variables that are only accessed internally by your class,
530such as utility and helper functions that your public methods use for
531code abstraction, should be prefixed with an underscore.
532
533::
534
Derek Jones129c1812011-10-05 17:15:44 -0500535 convert_text() // public method
536 _convert_text() // private method
Derek Jones8ede1a22011-10-05 13:34:52 -0500537
538PHP Errors
539==========
540
541Code must run error free and not rely on warnings and notices to be
542hidden to meet this requirement. For instance, never access a variable
543that you did not set yourself (such as $_POST array keys) without first
544checking to see that it isset().
545
546Make sure that while developing your add-on, error reporting is enabled
547for ALL users, and that display_errors is enabled in the PHP
548environment. You can check this setting with::
549
Derek Jones129c1812011-10-05 17:15:44 -0500550 if (ini_get('display_errors') == 1)
551 {
552 exit "Enabled";
553 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500554
555On some servers where display_errors is disabled, and you do not have
556the ability to change this in the php.ini, you can often enable it with::
557
558 ini_set('display_errors', 1);
559
560**NOTE:** Setting the
561`display_errors <http://us.php.net/manual/en/ref.errorfunc.php#ini.display-errors>`_
562setting with ini_set() at runtime is not identical to having it enabled
563in the PHP environment. Namely, it will not have any effect if the
564script has fatal errors
565
566Short Open Tags
567===============
568
569Always use full PHP opening tags, in case a server does not have
570short_open_tag enabled.
571
Derek Jones129c1812011-10-05 17:15:44 -0500572**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500573
Derek Jones129c1812011-10-05 17:15:44 -0500574 <? echo $foo; ?>
575
576 <?=$foo?>
577
578**CORRECT**::
579
580 <?php echo $foo; ?>
Derek Jones8ede1a22011-10-05 13:34:52 -0500581
582One Statement Per Line
583======================
584
585Never combine statements on one line.
586
Derek Jones129c1812011-10-05 17:15:44 -0500587**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500588
Derek Jones129c1812011-10-05 17:15:44 -0500589 $foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag);
590
591**CORRECT**::
592
593 $foo = 'this';
594 $bar = 'that';
595 $bat = str_replace($foo, $bar, $bag);
Derek Jones8ede1a22011-10-05 13:34:52 -0500596
597Strings
598=======
599
600Always use single quoted strings unless you need variables parsed, and
601in cases where you do need variables parsed, use braces to prevent
602greedy token parsing. You may also use double-quoted strings if the
603string contains single quotes, so you do not have to use escape
604characters.
605
Derek Jones129c1812011-10-05 17:15:44 -0500606**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500607
Derek Jones129c1812011-10-05 17:15:44 -0500608 "My String" // no variable parsing, so no use for double quotes
609 "My string $foo" // needs braces
610 'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly
611
612**CORRECT**::
613
614 'My String'
615 "My string {$foo}"
616 "SELECT foo FROM bar WHERE baz = 'bag'"
Derek Jones8ede1a22011-10-05 13:34:52 -0500617
618SQL Queries
619===========
620
621MySQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE,
622AS, JOIN, ON, IN, etc.
623
624Break up long queries into multiple lines for legibility, preferably
625breaking for each clause.
626
Derek Jones129c1812011-10-05 17:15:44 -0500627**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500628
Derek Jones129c1812011-10-05 17:15:44 -0500629 // keywords are lowercase and query is too long for
630 // a single line (... indicates continuation of line)
631 $query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses
632 ...where foo != 'oof' and baz != 'zab' order by foobaz limit 5, 100");
633
634**CORRECT**::
635
636 $query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz
637 FROM exp_pre_email_addresses
638 WHERE foo != 'oof'
639 AND baz != 'zab'
640 ORDER BY foobaz
641 LIMIT 5, 100");
Derek Jones8ede1a22011-10-05 13:34:52 -0500642
643Default Function Arguments
644==========================
645
646Whenever appropriate, provide function argument defaults, which helps
647prevent PHP errors with mistaken calls and provides common fallback
648values which can save a few lines of code. Example::
649
650 function foo($bar = '', $baz = FALSE)
651