blob: 2b91d1cc0429ec19bea20d7b313faf3dd242fc6f [file] [log] [blame]
Derek Jones619b1222011-10-10 16:26:27 -05001###############
2PHP Style Guide
3###############
4
Derek Jones8ede1a22011-10-05 13:34:52 -05005
6The following page describes the use of coding rules adhered to when
7developing CodeIgniter.
8
9.. contents:: Table of Contents
10
11File Format
12===========
13
14Files should be saved with Unicode (UTF-8) encoding. The BOM should
15*not* be used. Unlike UTF-16 and UTF-32, there's no byte order to
16indicate in a UTF-8 encoded file, and the BOM can have a negative side
17effect in PHP of sending output, preventing the application from being
18able to set its own headers. Unix line endings should be used (LF).
19
20Here is how to apply these settings in some of the more common text
21editors. Instructions for your text editor may vary; check your text
22editor's documentation.
23
24TextMate
25''''''''
26
27#. Open the Application Preferences
28#. Click Advanced, and then the "Saving" tab
29#. In "File Encoding", select "UTF-8 (recommended)"
30#. In "Line Endings", select "LF (recommended)"
31#. *Optional:* Check "Use for existing files as well" if you wish to
32 modify the line endings of files you open to your new preference.
33
34BBEdit
35''''''
36
37#. Open the Application Preferences
38#. Select "Text Encodings" on the left.
39#. In "Default text encoding for new documents", select "Unicode (UTF-8,
40 no BOM)"
41#. *Optional:* In "If file's encoding can't be guessed, use", select
42 "Unicode (UTF-8, no BOM)"
43#. Select "Text Files" on the left.
44#. In "Default line breaks", select "Mac OS X and Unix (LF)"
45
46PHP Closing Tag
47===============
48
49The PHP closing tag on a PHP document **?>** is optional to the PHP
50parser. However, if used, any whitespace following the closing tag,
51whether introduced by the developer, user, or an FTP application, can
52cause unwanted output, PHP errors, or if the latter are suppressed,
53blank pages. For this reason, all PHP files should **OMIT** the closing
54PHP tag, and instead use a comment block to mark the end of file and
55it's location relative to the application root. This allows you to still
56identify a file as being complete and not truncated.
57
Derek Jones129c1812011-10-05 17:15:44 -050058**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -050059
Derek Jones129c1812011-10-05 17:15:44 -050060 <?php
61
62 echo "Here's my code!";
63
64 ?>
65
66**CORRECT**::
67
68 <?php
69
70 echo "Here's my code!";
71
72 /* End of file myfile.php */
73 /* Location: ./system/modules/mymodule/myfile.php */
Derek Jones8ede1a22011-10-05 13:34:52 -050074
75Class and Method Naming
76=======================
77
78Class names should always start with an uppercase letter. Multiple words
79should be separated with an underscore, and not CamelCased. All other
80class methods should be entirely lowercased and named to clearly
81indicate their function, preferably including a verb. Try to avoid
82overly long and verbose names.
83
Derek Jones129c1812011-10-05 17:15:44 -050084**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -050085
Derek Jones129c1812011-10-05 17:15:44 -050086 class superclass
87 class SuperClass
88
89**CORRECT**::
90
91 class Super_class
Derek Jones8ede1a22011-10-05 13:34:52 -050092
93::
94
Derek Jones129c1812011-10-05 17:15:44 -050095 class Super_class {
Derek Jones8ede1a22011-10-05 13:34:52 -050096
Andrey Andreevd8e1ac72012-03-26 22:22:37 +030097 public function __construct()
Derek Jones129c1812011-10-05 17:15:44 -050098 {
Derek Jones8ede1a22011-10-05 13:34:52 -050099
Derek Jones129c1812011-10-05 17:15:44 -0500100 }
101 }
102
103Examples of improper and proper method naming:
104
105**INCORRECT**::
106
107 function fileproperties() // not descriptive and needs underscore separator
108 function fileProperties() // not descriptive and uses CamelCase
109 function getfileproperties() // Better! But still missing underscore separator
110 function getFileProperties() // uses CamelCase
111 function get_the_file_properties_from_the_file() // wordy
112
113**CORRECT**::
114
115 function get_file_properties() // descriptive, underscore separator, and all lowercase letters
Derek Jones8ede1a22011-10-05 13:34:52 -0500116
117Variable Names
118==============
119
120The guidelines for variable naming is very similar to that used for
121class methods. Namely, variables should contain only lowercase letters,
122use underscore separators, and be reasonably named to indicate their
123purpose and contents. Very short, non-word variables should only be used
124as iterators in for() loops.
125
Derek Jones129c1812011-10-05 17:15:44 -0500126**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500127
Derek Jones129c1812011-10-05 17:15:44 -0500128 $j = 'foo'; // single letter variables should only be used in for() loops
129 $Str // contains uppercase letters
130 $bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning
131 $groupid // multiple words, needs underscore separator
132 $name_of_last_city_used // too long
133
134**CORRECT**::
135
136 for ($j = 0; $j < 10; $j++)
137 $str
138 $buffer
139 $group_id
140 $last_city
Derek Jones8ede1a22011-10-05 13:34:52 -0500141
142Commenting
143==========
144
145In general, code should be commented prolifically. It not only helps
146describe the flow and intent of the code for less experienced
147programmers, but can prove invaluable when returning to your own code
148months down the line. There is not a required format for comments, but
149the following are recommended.
150
151`DocBlock <http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html#basics.docblock>`_
152style comments preceding class and method declarations so they can be
153picked up by IDEs::
154
Derek Jones129c1812011-10-05 17:15:44 -0500155 /**
156 * Super Class
157 *
158 * @package Package Name
159 * @subpackage Subpackage
160 * @category Category
161 * @author Author Name
162 * @link http://example.com
163 */
164 class Super_class {
Derek Jones8ede1a22011-10-05 13:34:52 -0500165
166::
167
Derek Jones129c1812011-10-05 17:15:44 -0500168 /**
169 * Encodes string for use in XML
170 *
Derek Jones129c1812011-10-05 17:15:44 -0500171 * @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 }
Timothy Warren82c83072012-01-26 19:02:05 -0500443
444 try {
445 // ...
446 }
447 catch() {
448 // ...
449 }
Derek Jones129c1812011-10-05 17:15:44 -0500450
451**CORRECT**::
452
453 function foo($bar)
454 {
455 // ...
456 }
457
458 foreach ($arr as $key => $val)
459 {
460 // ...
461 }
462
463 if ($foo == $bar)
464 {
465 // ...
466 }
467 else
468 {
469 // ...
470 }
471
472 for ($i = 0; $i < 10; $i++)
473 {
474 for ($j = 0; $j < 10; $j++)
475 {
476 // ...
477 }
478 }
Timothy Warren82c83072012-01-26 19:02:05 -0500479
480 try
481 {
482 // ...
483 }
484 catch()
485 {
486 // ...
487 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500488
489Bracket and Parenthetic Spacing
490===============================
491
492In general, parenthesis and brackets should not use any additional
493spaces. The exception is that a space should always follow PHP control
494structures that accept arguments with parenthesis (declare, do-while,
495elseif, for, foreach, if, switch, while), to help distinguish them from
496functions and increase readability.
497
Derek Jones129c1812011-10-05 17:15:44 -0500498**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500499
Derek Jones129c1812011-10-05 17:15:44 -0500500 $arr[ $foo ] = 'foo';
501
502**CORRECT**::
503
504 $arr[$foo] = 'foo'; // no spaces around array keys
505
506**INCORRECT**::
507
508 function foo ( $bar )
509 {
510
511 }
512
513**CORRECT**::
514
515 function foo($bar) // no spaces around parenthesis in function declarations
516 {
517
518 }
519
520**INCORRECT**::
521
522 foreach( $query->result() as $row )
523
524**CORRECT**::
525
526 foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis
Derek Jones8ede1a22011-10-05 13:34:52 -0500527
528Localized Text
529==============
530
531Any text that is output in the control panel should use language
532variables in your lang file to allow localization.
533
Derek Jones129c1812011-10-05 17:15:44 -0500534**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500535
Derek Jones129c1812011-10-05 17:15:44 -0500536 return "Invalid Selection";
537
538**CORRECT**::
539
540 return $this->lang->line('invalid_selection');
Derek Jones8ede1a22011-10-05 13:34:52 -0500541
542Private Methods and Variables
543=============================
544
545Methods and variables that are only accessed internally by your class,
546such as utility and helper functions that your public methods use for
547code abstraction, should be prefixed with an underscore.
548
549::
550
Derek Jones129c1812011-10-05 17:15:44 -0500551 convert_text() // public method
552 _convert_text() // private method
Derek Jones8ede1a22011-10-05 13:34:52 -0500553
554PHP Errors
555==========
556
557Code must run error free and not rely on warnings and notices to be
558hidden to meet this requirement. For instance, never access a variable
559that you did not set yourself (such as $_POST array keys) without first
560checking to see that it isset().
561
562Make sure that while developing your add-on, error reporting is enabled
563for ALL users, and that display_errors is enabled in the PHP
564environment. You can check this setting with::
565
Derek Jones129c1812011-10-05 17:15:44 -0500566 if (ini_get('display_errors') == 1)
567 {
568 exit "Enabled";
569 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500570
571On some servers where display_errors is disabled, and you do not have
572the ability to change this in the php.ini, you can often enable it with::
573
574 ini_set('display_errors', 1);
575
576**NOTE:** Setting the
577`display_errors <http://us.php.net/manual/en/ref.errorfunc.php#ini.display-errors>`_
578setting with ini_set() at runtime is not identical to having it enabled
579in the PHP environment. Namely, it will not have any effect if the
580script has fatal errors
581
582Short Open Tags
583===============
584
585Always use full PHP opening tags, in case a server does not have
586short_open_tag enabled.
587
Derek Jones129c1812011-10-05 17:15:44 -0500588**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500589
Derek Jones129c1812011-10-05 17:15:44 -0500590 <? echo $foo; ?>
591
592 <?=$foo?>
593
594**CORRECT**::
595
596 <?php echo $foo; ?>
Derek Jones8ede1a22011-10-05 13:34:52 -0500597
598One Statement Per Line
599======================
600
601Never combine statements on one line.
602
Derek Jones129c1812011-10-05 17:15:44 -0500603**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500604
Derek Jones129c1812011-10-05 17:15:44 -0500605 $foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag);
606
607**CORRECT**::
608
609 $foo = 'this';
610 $bar = 'that';
611 $bat = str_replace($foo, $bar, $bag);
Derek Jones8ede1a22011-10-05 13:34:52 -0500612
613Strings
614=======
615
616Always use single quoted strings unless you need variables parsed, and
617in cases where you do need variables parsed, use braces to prevent
618greedy token parsing. You may also use double-quoted strings if the
619string contains single quotes, so you do not have to use escape
620characters.
621
Derek Jones129c1812011-10-05 17:15:44 -0500622**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500623
Derek Jones129c1812011-10-05 17:15:44 -0500624 "My String" // no variable parsing, so no use for double quotes
625 "My string $foo" // needs braces
626 'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly
627
628**CORRECT**::
629
630 'My String'
631 "My string {$foo}"
632 "SELECT foo FROM bar WHERE baz = 'bag'"
Derek Jones8ede1a22011-10-05 13:34:52 -0500633
634SQL Queries
635===========
636
637MySQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE,
638AS, JOIN, ON, IN, etc.
639
640Break up long queries into multiple lines for legibility, preferably
641breaking for each clause.
642
Derek Jones129c1812011-10-05 17:15:44 -0500643**INCORRECT**::
Derek Jones8ede1a22011-10-05 13:34:52 -0500644
Derek Jones129c1812011-10-05 17:15:44 -0500645 // keywords are lowercase and query is too long for
646 // a single line (... indicates continuation of line)
647 $query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses
648 ...where foo != 'oof' and baz != 'zab' order by foobaz limit 5, 100");
649
650**CORRECT**::
651
652 $query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz
653 FROM exp_pre_email_addresses
654 WHERE foo != 'oof'
655 AND baz != 'zab'
656 ORDER BY foobaz
657 LIMIT 5, 100");
Derek Jones8ede1a22011-10-05 13:34:52 -0500658
659Default Function Arguments
660==========================
661
662Whenever appropriate, provide function argument defaults, which helps
663prevent PHP errors with mistaken calls and provides common fallback
664values which can save a few lines of code. Example::
665
666 function foo($bar = '', $baz = FALSE)
667