blob: 9d49a9d03d90b337f61d208f8788364655973e2a [file] [log] [blame]
Rick Ellis5a9fd7a2008-08-31 05:58:32 +00001<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
3<head>
4
5<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6<title>Security : CodeIgniter User Guide</title>
7
8<style type='text/css' media='all'>@import url('../userguide.css');</style>
9<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />
10
11<style type="text/css" media="screen">
12 code {
13 white-space: pre;
14 }
15</style>
16
17<script type="text/javascript" src="../nav/nav.js"></script>
18<script type="text/javascript" src="../nav/prototype.lite.js"></script>
19<script type="text/javascript" src="../nav/moo.fx.js"></script>
20<script type="text/javascript" src="../nav/user_guide_menu.js"></script>
21
22<meta http-equiv='expires' content='-1' />
23<meta http-equiv= 'pragma' content='no-cache' />
24<meta name='robots' content='all' />
25<meta name='author' content='ExpressionEngine Dev Team' />
26<meta name='description' content='CodeIgniter User Guide' />
27
28</head>
29<body>
30
31<!-- START NAVIGATION -->
32<div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div>
33<div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div>
34<div id="masthead">
35<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
36<tr>
37<td><h1>CodeIgniter User Guide Version 1.7</h1></td>
38<td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td>
39</tr>
40</table>
41</div>
42<!-- END NAVIGATION -->
43
44
45<!-- START BREADCRUMB -->
46<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
47<tr>
48<td id="breadcrumb">
49<a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp;
50<a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp;
51Security
52</td>
53<td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/user_guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td>
54</tr>
55</table>
56<!-- END BREADCRUMB -->
57
58<br clear="all" />
59
60
61<!-- START CONTENT -->
62<div id="content">
63
64
65<h1>General Style and Syntax</h1>
66
67<p>The following page describes the coding rules use adhere to when developing CodeIgniter.</p>
68
69
70<h2>Table of Contents</h2>
71<ul class="minitoc">
72 <li><a href="#php_closing_tag">PHP Closing Tag</a></li>
73 <li><a href="#class_and_method_naming">Class and Method Naming</a></li>
74 <li><a href="#variable_names">Variable Names</a></li>
75 <li><a href="#commenting">Commenting</a></li>
76 <li><a href="#constants">Constants</a></li>
77 <li><a href="#true_false_and_null">TRUE, FALSE, and NULL</a></li>
78 <li><a href="#logical_operators">Logical Operators</a></li>
79 <li><a href="#comparing_return_values_and_typecasting">Comparing Return Values and Typecasting</a></li>
80 <li><a href="#debugging_code">Debugging Code</a></li>
81 <li><a href="#whitespace_in_files">Whitespace in Files</a></li>
82 <li><a href="#compatibility">Compatibility</a></li>
83 <li><a href="#use_of_sess_cache">Use of $SESS->cache</a></li>
84 <li><a href="#class_and_file_names_using_common_words">Class and File Names using Common Words</a></li>
85 <li><a href="#database_table_names">Database Table Names</a></li>
86 <li><a href="#one_file_per_class">One File per Class</a></li>
87 <li><a href="#whitespace">Whitespace</a></li>
88 <li><a href="#line_breaks">Line Breaks</a></li>
89 <li><a href="#code_indenting">Code Indenting</a></li>
90 <li><a href="#bracket_spacing">Bracket and Parenthetic Spacing</li>
91 <li><a href="#localized_text_in_control_panel">Localized Text in Control Panel</a></li>
92 <li><a href="#private_methods_and_variables">Private Methods and Variables</a></li>
93 <li><a href="#php_errors">PHP Errors</a></li>
94 <li><a href="#short_open_tags">Short Open Tags</a></li>
95 <li><a href="#one_statement_per_line">One Statement Per Line</a></li>
96 <li><a href="#strings">Strings</a></li>
97 <li><a href="#sql_queries">SQL Queries</a></li>
98 <li><a href="#default_function_arguments">Default Function Arguments</a></li>
99 <li><a href="#overlapping_tag_parameters">Overlapping Tag Parameters</a></li>
100</ul>
101
102 <h2><a name="php_closing_tag"></a>PHP Closing Tag</h2>
103 <div class="guidelineDetails">
104 <p>The PHP closing tag on a PHP document <strong>?&gt;</strong> is optional to the PHP parser. However, if used, any whitespace following the closing tag, whether introduced
105 by the developer, user, or an FTP application, can cause unwanted output, PHP errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should
106 <strong>OMIT</strong> the closing PHP tag, and instead use a comment block to mark the end of file and it's location relative to the application root.
107 This allows you to still identify a file as being complete and not truncated.</p>
108<code><strong>INCORRECT</strong>:
109&lt;?php
110
111echo "Here's my code!";
112
113?&gt;
114
115<strong>CORRECT</strong>:
116&lt;?php
117
118echo "Here's my code!";
119
120/* End of file myfile.php */
121/* Location: ./system/modules/mymodule/myfile.php */
122</code>
123 </div>
124
125
126 <h2><a name="class_and_method_naming"></a>Class and Method Naming</h2>
127 <div class="guidelineDetails">
128 <p>Class names should always have their first letter uppercase, and the constructor method should match identically. Multiple words should be separated with an underscore, and not CamelCased. All other class methods should be entirely lowercased and named to clearly indicate their function, preferably including a verb. Try to avoid overly long and verbose names.</p>
129
130 <code><strong>INCORRECT</strong>:
131class superclass
132class SuperClass
133
134<strong>CORRECT</strong>:
135class Super_class</code>
136
137 <p>Notice that the Class and constructor methods are identically named and cased:</p>
138
139 <code>class Super_class {
140
141 function Super_class()
142 {
143
144 }
145}</code>
146
147 <p>Examples of improper and proper method naming:</p>
148
149 <code><strong>INCORRECT</strong>:
150function fileproperties() // not descriptive and needs underscore separator
151function fileProperties() // not descriptive and uses CamelCase
152function getfileproperties() // Better! But still missing underscore separator
153function getFileProperties() // uses CamelCase
154function get_the_file_properties_from_the_file() // wordy
155
156<strong>CORRECT</strong>:
157function get_file_properties() // descriptive, underscore separator, and all lowercase letters</code>
158
159 </div>
160
161
162 <h2><a name="variable_names"></a>Variable Names</h2>
163 <div class="guidelineDetails">
164 <p>The guidelines for variable naming is very similar to that used for class methods. Namely, variables should contain only lowercase letters, use underscore separators, and be reasonably named to indicate their purpose and contents. Very short, non-word variables should only be used as iterators in for() loops.</p>
165<code><strong>INCORRECT</strong>:
166$j = &apos;foo&apos;; // single letter variables should only be used in for() loops
167$Str // contains uppercase letters
168$bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning
169$groupid // multiple words, needs underscore separator
170$name_of_last_city_used // too long
171
172<strong>CORRECT</strong>:
173for ($j = 0; $j &lt; 10; $j++)
174$str
175$buffer
176$group_id
177$last_city
178</code>
179 </div>
180
181
182 <h2><a name="commenting"></a>Commenting</h2>
183 <div class="guidelineDetails">
184 <p>In general, code should be commented prolifically. It not only helps describe the flow and intent of the code for less experienced programmers, but can prove invaluable when returning to your own code months down the line. There is not a required format for comments, but the following are recommended.</p>
185
186 <p><a href="http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html#basics.docblock">DocBlock</a> style comments preceding class and method declarations so they can be picked up by IDEs:</p>
187
188<code>/**
189 * Super Class
190 *
191 * @package Package Name
192 * @subpackage Subpackage
193 * @category Category
194 * @author Author Name
195 * @link http://example.com
196 */
197class Super_class {</code>
198
199<code>/**
200 * Encodes string for use in XML
201 *
202 * @access public
203 * @param string
204 * @return string
205 */
206function xml_encode($str)</code>
207
208 <p>Use single line comments within code, leaving a blank line between large comment blocks and code.</p>
209
210<code>// break up the string by newlines
211$parts = explode("\n", $str);
212
213// A longer comment that needs to give greater detail on what is
214// occurring and why can use multiple single-line comments. Try to
215// keep the width reasonable, around 70 characters is the easiest to
216// read. Don't hesitate to link to permanent external resources
217// that may provide greater detail:
218//
219// http://example.com/information_about_something/in_particular/
220
221$parts = $this->foo($parts);
222</code>
223 </div>
224
225
226 <h2><a name="constants"></a>Constants</h2>
227 <div class="guidelineDetails">
228 <p>Constants follow the same guidelines as do variables, except constants should always be fully uppercase. <em>Always use ExpressionEngine constants when appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc.</em></p>
229<code><strong>INCORRECT</strong>:
230myConstant // missing underscore separator and not fully uppercase
231N // no single-letter constants
232S_C_VER // not descriptive
233$str = str_replace('{foo}', 'bar', $str); // should use LD and RD constants
234
235<strong>CORRECT</strong>:
236MY_CONSTANT
237NEWLINE
238SUPER_CLASS_VERSION
239$str = str_replace(LD.'foo'.RD, 'bar', $str);
240</code>
241 </div>
242
243
244 <h2><a name="true_false_and_null"></a>TRUE, FALSE, and NULL</h2>
245 <div class="guidelineDetails">
246 <p><strong>TRUE</strong>, <strong>FALSE</strong>, and <strong>NULL</strong> keywords should always be fully uppercase.</p>
247<code><strong>INCORRECT</strong>:
248if ($foo == true)
249$bar = false;
250function foo($bar = null)
251
252<strong>CORRECT</strong>:
253if ($foo == TRUE)
254$bar = FALSE;
255function foo($bar = NULL)</code>
256 </div>
257
258
259
260 <h2><a name="logical_operators"></a>Logical Operators</h2>
261 <div class="guidelineDetails">
262 <p>Use of <strong>||</strong> is discouraged as its clarity on some output devices is low (looking like the number 11 for instance).
263 <strong>&amp;&amp;</strong> is preferred over <strong>AND</strong> but either are acceptable, and a space should always precede and follow <strong>!</strong>.</p>
264<code><strong>INCORRECT</strong>:
265if ($foo || $bar)
266if ($foo AND $bar) // okay but not recommended for common syntax highlighting applications
267if (!$foo)
268if (! is_array($foo))
269
270<strong>CORRECT</strong>:
271if ($foo OR $bar)
272if ($foo && $bar) // recommended
273if ( ! $foo)
274if ( ! is_array($foo))
275</code>
276 </div>
277
278
279
280 <h2><a name="comparing_return_values_and_typecasting"></a>Comparing Return Values and Typecasting</h2>
281 <div class="guidelineDetails">
282 <p>Some PHP functions return FALSE on failure, but may also have a valid return value of "" or 0, which would evaluate to FALSE in loose comparisons. Be explicit by comparing the variable type when using these return values in conditionals to ensure the return value is indeed what you expect, and not a value that has an equivalent loose-type evaluation.</p>
283 <p>Use the same stringency in returning and checking your own variables. Use <strong>===</strong> and <strong>!==</strong> as necessary.
284
285<code><strong>INCORRECT</strong>:
286// If 'foo' is at the beginning of the string, strpos will return a 0,
287// resulting in this conditional evaluating as TRUE
288if (strpos($str, 'foo') == FALSE)
289
290<strong>CORRECT</strong>:
291if (strpos($str, 'foo') === FALSE)
292</code>
293
294<code><strong>INCORRECT</strong>:
295function build_string($str = "")
296{
297 if ($str == "") // uh-oh! What if FALSE or the integer 0 is passed as an argument?
298 {
299
300 }
301}
302
303<strong>CORRECT</strong>:
304function build_string($str = "")
305{
306 if ($str === "")
307 {
308
309 }
310}</code>
311
312 <p>See also information regarding <a href="http://us3.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting">typecasting</a>, which can be quite useful. Typecasting has a slightly different effect which may be desirable. When casting a variable as a string, for instance, NULL and boolean FALSE variables become empty strings, 0 (and other numbers) become strings of digits, and boolean TRUE becomes "1":</p>
313
314<code>$str = (string) $str; // cast $str as a string</code>
315
316 </div>
317
318
319 <h2><a name="debugging_code"></a>Debugging Code</h2>
320 <div class="guidelineDetails">
321 <p>No debugging code can be left in place for submitted add-ons unless it is commented out, i.e. no var_dump(), print_r(), die(), and exit() calls that were used while creating the add-on, unless they are commented out.</p>
322
323<code>// print_r($foo);</code>
324 </div>
325
326
327
328 <h2><a name="whitespace_in_files"></a>Whitespace in Files</h2>
329 <div class="guidelineDetails">
330 <p>No whitespace can precede the opening PHP tag or follow the closing PHP tag. ExpressionEngine output is buffered, so whitespace in your files can cause output to begin before ExpressionEngine outputs its content, leading to errors and an inability for ExpressionEngine to send proper headers. In the examples below, select the text with your mouse to reveal the incorrect whitespace.</p>
331
332 <p><strong>INCORRECT</strong>:</p>
333<code>
334&lt;?php
335 // ...there is whitespace and a linebreak above the opening PHP tag
336 // as well as whitespace after the closing PHP tag
337?&gt;
338</code>
339 <p><strong>CORRECT</strong>:</p>
340<code>&lt;?php
341 // this sample has no whitespace before or after the opening and closing PHP tags
342?&gt;</code>
343
344 </div>
345
346
347 <h2><a name="compatibility"></a>Compatibility</h2>
348 <div class="guidelineDetails">
349 <p>Unless specifically mentioned in your add-on's documentation, all code must be compatible with PHP version 4.3+. Additionally, do not use PHP functions that require non-default libraries to be installed unless your code contains an alternative method when the function is not available, or you implicitly document that your add-on requires said PHP libraries.</p>
350 </div>
351
352
353 <h2><a name="use_of_sess_cache"></a>Use of $SESS->cache</h2>
354 <div class="guidelineDetails">
355 <p>$SESS->cache is an array provided for you to use for "flash" content, i.e. values that you would like to persist during a page load, helping you eliminate redundant queries and PHP processing. To avoid conflicts with other first and third-party use of this array, always access it as a multi-dimensional array, using your class name as the primary array name, and your variables within. Naming conventions should follow that of other variables: lowercase letters, underscores for separators between words, and meaningful names.</p>
356
357<code><strong>INCORRECT</strong>:
358$SESS->cache['admins']
359$SESS->cache['Super_class']['admins']
360
361<strong>CORRECT</strong>:
362$SESS->cache['super_class']['admins']</code>
363
364 <p>Here is an example of how one might utilize the $SESS->cache array. This way, no matter how many times this method is called on a given page load (for instance, a tag being used twice on a template, or within a tag that might loop, such as a plugin within the Weblog entries tag), the query and loading of the array occurs only once.</p>
365
366<code>if ( ! isset($SESS->cache['super_class']['admins']))
367{
368 $query = $DB->query("SELECT member_id FROM exp_super_class_admins");
369
370 if ($query->num_rows > 0)
371 {
372 foreach ($query->result as $row)
373 {
374 $SESS->cache['super_class']['admins'][] = $row['member_id'];
375 }
376 }
377}
378
379// set a local variable from the cached global so it's easy to use in the code
380$admins = $SESS->cache['super_class']['admins'];
381</code>
382 <p>You can see an example of real-world usage of $SESS->cache in the Weblog module's <samp>fetch_custom_weblog_fields()</samp> and <samp>next_prev_entry()</samp> methods, and the IP to Nation module's <samp>get_country()</samp> method.</p>
383
384 </div>
385
386
387
388 <h2><a name="class_and_file_names_using_common_words"></a>Class and File Names using Common Words</h2>
389 <div class="guidelineDetails">
390 <p>When your class or filename is a common word, or might quite likely be identically named in another PHP script, provide a unique prefix to help prevent collision. Always realize that your end users may be running other add-ons or third party PHP scripts. Choose a prefix that is unique to your identity as a developer or company.</p>
391
392<code><strong>INCORRECT</strong>:
393class Email pi.email.php
394class Xml ext.xml.php
395class Import mod.import.php
396
397<strong>CORRECT</strong>:
398class Pre_email pi.pre_email.php
399class Pre_xml ext.pre_xml.php
400class Pre_import mod.pre_import.php
401</code>
402 </div>
403
404
405 <h2><a name="database_table_names"></a>Database Table Names</h2>
406 <div class="guidelineDetails">
407 <p>Any tables that your add-on might use must use the 'exp_' prefix, followed by a prefix uniquely identifying you as the developer or company, and then a short descriptive table name. You do not need to be concerned about the database prefix being used on the user's installation, as ExpressionEngine's database class will automatically convert 'exp_' to what is actually being used.</p>
408
409<code><strong>INCORRECT</strong>:
410email_addresses // missing both prefixes
411pre_email_addresses // missing exp_ prefix
412exp_email_addresses // missing unique prefix
413
414<strong>CORRECT</strong>:
415exp_pre_email_addresses
416</code>
417
418 <p class="important"><strong>NOTE:</strong> Be mindful that MySQL has a limit of 64 characters for table names. This should not be an issue as table names that would exceed this would likely have unreasonable names. For instance, the following table name exceeds this limitation by one character. Silly, no? <strong>exp_pre_email_addresses_of_registered_users_in_seattle_washington</strong>
419 </div>
420
421
422
423 <h2><a name="one_file_per_class"></a>One File per Class</h2>
424 <div class="guidelineDetails">
425 <p>Use separate files for each class your add-on uses, unless the classes are <em>closely related</em>. An example of ExpressionEngine files that contains multiple classes is the Database class file, which contains both the DB class and the DB_Cache class, and the Magpie plugin, which contains both the Magpie and Snoopy classes.</p>
426 </div>
427
428
429
430 <h2><a name="whitespace"></a>Whitespace</h2>
431 <div class="guidelineDetails">
432 <p>Use tabs for whitespace in your code, not spaces. This may seem like a small thing, but using tabs instead of whitespace allows the developer looking at your code to have indentation at levels that they prefer and customize in whatever application they use. And as a side benefit, it results in (slightly) more compact files, storing one tab character versus, say, four space characters.</p>
433 </div>
434
435
436
437 <h2><a name="line_breaks"></a>Line Breaks</h2>
438 <div class="guidelineDetails">
439 <p>Files must be saved with Unix line breaks. This is more of an issue for developers who work in Windows, but in any case ensure that your text editor is setup to save files with Unix line breaks.</p>
440 </div>
441
442
443
444 <h2><a name="code_indenting"></a>Code Indenting</h2>
445 <div class="guidelineDetails">
446 <p>Use Allman style indenting. With the exception of Class declarations, braces are always placed on a line by themselves, and indented at the same level as the control statement that "owns" them.</p>
447
448<code><strong>INCORRECT</strong>:
449function foo($bar) {
450 // ...
451}
452
453foreach ($arr as $key => $val) {
454 // ...
455}
456
457if ($foo == $bar) {
458 // ...
459} else {
460 // ...
461}
462
463for ($i = 0; $i &lt; 10; $i++)
464 {
465 for ($j = 0; $j &lt; 10; $j++)
466 {
467 // ...
468 }
469 }
470
471<strong>CORRECT</strong>:
472function foo($bar)
473{
474 // ...
475}
476
477foreach ($arr as $key => $val)
478{
479 // ...
480}
481
482if ($foo == $bar)
483{
484 // ...
485}
486else
487{
488 // ...
489}
490
491for ($i = 0; $i &lt; 10; $i++)
492{
493 for ($j = 0; $j &lt; 10; $j++)
494 {
495 // ...
496 }
497}</code>
498 </div>
499
500
501 <h2><a name="bracket_spacing"></a>Bracket and Parenthetic Spacing</h2>
502 <div class="guidelineDetails">
503 <p>In general, parenthesis and brackets should not use any additional spaces. The exception is that a space should always follow PHP control structures that accept arguments with parenthesis (declare, do-while, elseif, for, foreach, if, switch, while), to help distinguish them from functions and increase readability.</p>
504
505<code>INCORRECT:
506$arr[ $foo ] = 'foo';
507
508CORRECT:
509$arr[$foo] = 'foo'; // no spaces around array keys
510
511
512INCORRECT:
513function foo ( $bar )
514{
515
516}
517
518CORRECT:
519function foo($bar) // no spaces around parenthesis in function declarations
520{
521
522}
523
524
525INCORRECT:
526foreach( $query->result as $row )
527
528CORRECT:
529foreach ($query->result as $row) // single space following PHP control structures, but not in interior parenthesis
530</code>
531 </div>
532
533
534
535 <h2><a name="localized_text_in_control_panel"></a>Localized Text in Control Panel</h2>
536 <div class="guidelineDetails">
537 <p>Any text that is output in the control panel should use language variables in your module's lang file to allow localization.</p>
538
539<code>INCORRECT:
540return "Invalid Selection";
541
542CORRECT:
543return $LANG->line('invalid_selection');</code>
544 </div>
545
546
547
548 <h2><a name="private_methods_and_variables"></a>Private Methods and Variables</h2>
549 <div class="guidelineDetails">
550 <p>Methods and variables that are only accessed internally by your class, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore.</p>
551
552<code>convert_text() // public method
553_convert_text() // private method</code>
554 </div>
555
556
557
558 <h2><a name="php_errors"></a>PHP Errors</h2>
559 <div class="guidelineDetails">
560 <p>Code must run error free and not rely on warnings and notices to be hidden to meet this requirement. For instance, never access a variable that you did not set yourself (such as $_POST array keys) without first checking to see that it isset().</p>
561
562 <p>Make sure that while developing your add-on, error reporting is enabled for ALL users, and that display_errors is enabled in the PHP environment. You can check this setting with:</p>
563
564<code>if (ini_get('display_errors') == 1)
565{
566 exit "Enabled";
567}</code>
568
569 <p>On some servers where display_errors is disabled, and you do not have the ability to change this in the php.ini, you can often enable it with:</p>
570
571<code>ini_set('display_errors', 1);</code>
572
573 <p class="important"><strong>NOTE:</strong> Setting the <a href="http://us.php.net/manual/en/ref.errorfunc.php#ini.display-errors">display_errors</a> setting with ini_set() at runtime is not identical to having it enabled in the PHP environment. Namely, it will not have any effect if the script has fatal errors</p>
574 </div>
575
576
577
578 <h2><a name="short_open_tags"></a>Short Open Tags</h2>
579 <div class="guidelineDetails">
580 <p>Always use full PHP opening tags, in case a server does not have short_open_tag enabled.</p>
581
582<code><strong>INCORRECT</strong>:
583&lt;? echo $foo; ?&gt;
584
585&lt;?=$foo?&gt;
586
587<strong>CORRECT</strong>:
588&lt;?php echo $foo; ?&gt;</code>
589 </div>
590
591
592
593 <h2><a name="one_statement_per_line"></a>One Statement Per Line</h2>
594 <div class="guidelineDetails">
595 <p>Never combine statements on one line.</p>
596
597<code><strong>INCORRECT</strong>:
598$foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag);
599
600<strong>CORRECT</strong>:
601$foo = 'this';
602$bar = 'that';
603$bat = str_replace($foo, $bar, $bag);
604</code>
605 </div>
606
607
608
609 <h2><a name="strings"></a>Strings</h2>
610 <div class="guidelineDetails">
611 <p>Always use single quoted strings unless you need variables parsed, and in cases where you do need variables parsed, use braces to prevent greedy token parsing. You may also use double-quoted strings if the string contains single quotes, so you do not have to use escape characters.</p>
612
613<code><strong>INCORRECT</strong>:
614"My String" // no variable parsing, so no use for double quotes
615"My string $foo" // needs braces
616'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly
617
618<strong>CORRECT</strong>:
619'My String'
620"My string {$foo}"
621"SELECT foo FROM bar WHERE baz = 'bag'"</code>
622 </div>
623
624
625
626 <h2><a name="sql_queries"></a>SQL Queries</h2>
627 <div class="guidelineDetails">
628 <p>MySQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, AS, JOIN, ON, IN, etc.</p>
629
630 <p>Break up long queries into multiple lines for legibility, preferably breaking for each clause.</p>
631
632<code><strong>INCORRECT</strong>:
633// keywords are lowercase and query is too long for
634// a single line (... indicates continuation of line)
635$query = $DB->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses
636...where foo != 'oof' and baz != 'zab' order by foobaz limit 5, 100");
637
638<strong>CORRECT</strong>:
639$query = $DB->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz
640 FROM exp_pre_email_addresses
641 WHERE foo != 'oof'
642 AND baz != 'zab'
643 ORDER BY foobaz
644 LIMIT 5, 100");</code>
645 </div>
646
647
648
649 <h2><a name="default_function_arguments"></a>Default Function Arguments</h2>
650 <div class="guidelineDetails">
651 <p>Whenever appropriate, provide function argument defaults, which helps prevent PHP errors with mistaken calls and provides common fallback values which can save a few lines of code. Example:</p>
652
653<code>function foo($bar = '', $baz = FALSE)</code>
654 </div>
655
656
657
658 <h2><a name="overlapping_tag_parameters"></a>Overlapping Tag Parameters</h2>
659 <div class="guidelineDetails">
660 <p>Avoid multiple tag parameters that have effect on the same thing. For instance, instead of <strong>include=</strong> and <strong>exclude=</strong>, perhaps allow <strong>include=</strong> to handle the parameter alone, with the addition of "not", e.g. <strong>include="not bar"</strong>. This will prevent problems of parameters overlapping or having to worry about which parameter has priority over another.</p>
661 </div>
662
663
664</div>
665
666
667
668</div>
669<!-- END CONTENT -->
670
671
672<div id="footer">
673<p>
674Previous Topic:&nbsp;&nbsp;<a href="security.html">Security</a>
675&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
676<a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
677<a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
678Next Topic:&nbsp;&nbsp;<a href="../doc_style/index.html">Writing Documentation</a>
679</p>
680<p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006-2008 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">Ellislab, Inc.</a></p>
681</div>
682
683</body>
684</html>