forked from phpbb/phpbb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoding-guidelines.html
2572 lines (2020 loc) · 111 KB
/
coding-guidelines.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="keywords" content="" />
<meta name="description" content="Rhea coding guidelines document" />
<title>phpBB3 • Coding Guidelines</title>
<link href="assets/css/stylesheet.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body id="phpbb" class="section-docs">
<div id="wrap">
<a id="top" name="top" accesskey="t"></a>
<div id="page-header">
<div class="headerbar">
<div class="inner">
<div id="doc-description">
<a href="../index.php" id="logo"><img src="assets/images/site_logo.gif" alt="" /></a>
<h1>Coding Guidelines</h1>
<p>Rhea coding guidelines document</p>
<p style="display: none;"><a href="#start_here">Skip</a></p>
</div>
</div>
</div>
</div>
<a name="start_here"></a>
<div id="page-body">
<!-- BEGIN DOCUMENT -->
<p class="paragraph main-description">
These are the phpBB Coding Guidelines for Rhea, all attempts should be made to follow them as closely as possible.
</p>
<h1>Coding Guidelines</h1>
<div class="paragraph menu">
<div class="inner">
<div class="content">
<ol>
<li><a href="#defaults">Defaults</a>
<ol style="list-style-type: lower-roman;">
<li><a href="#editorsettings">Editor Settings</a></li>
<li><a href="#fileheader">File Header</a></li>
<li><a href="#locations">File Locations</a></li>
<li><a href="#constants">Special Constants</a></li>
</ol>
</li>
<li><a href="#code">Code Layout/Guidelines</a>
<ol style="list-style-type: lower-roman;">
<li><a href="#namingvars">Variable/Function/Class Naming</a></li>
<li><a href="#codelayout">Code Layout</a></li>
<li><a href="#sql">SQL/SQL Layout</a></li>
<li><a href="#optimizing">Optimizations</a></li>
<li><a href="#general">General Guidelines</a></li>
<li><a href="#phprestrictions">Restrictions on the Use of PHP</a></li>
</ol>
</li>
<li><a href="#styling">Styling</a>
<ol style="list-style-type: lower-roman;">
<li><a href="#cfgfiles">Style Config Files</a></li>
<li><a href="#genstyling">General Styling Rules</a></li>
</ol></li>
<li><a href="#templating">Templating</a>
<ol style="list-style-type: lower-roman;">
<li><a href="#templates">General Templating</a></li>
<li><a href="#stylestree">Styles Tree</a></li>
<li><a href="#template-events">Template Events</a></li>
</ol></li>
<li><a href="#charsets">Character Sets and Encodings</a></li>
<li><a href="#translation">Translation (<abbr title="Internationalisation">i18n</abbr>/<abbr title="Localisation">L10n</abbr>) Guidelines</a>
<ol style="list-style-type: lower-roman;">
<li><a href="#standardisation">Standardisation</a></li>
<li><a href="#otherconsiderations">Other considerations</a></li>
<li><a href="#placeholders">Working with placeholders</a></li>
<li><a href="#usingplurals">Using plurals</a></li>
<li><a href="#writingstyle">Writing Style</a></li>
</ol>
</li>
<li><a href="#disclaimer">Copyright and disclaimer</a></li>
</ol>
</div>
</div>
</div>
<hr />
<a name="defaults"></a><h2>1. Defaults</h2>
<div class="paragraph">
<div class="inner">
<div class="content">
<a name="editorsettings"></a><h3>1.i. Editor Settings</h3>
<h4>Tabs vs Spaces:</h4>
<p>In order to make this as simple as possible, we will be using tabs, not spaces. We enforce 4 (four) spaces for one tab - therefore you need to set your tab width within your editor to 4 spaces. Make sure that when you <strong>save</strong> the file, it's saving tabs and not spaces. This way, we can each have the code be displayed the way we like it, without breaking the layout of the actual files.</p>
<p>Tabs in front of lines are no problem, but having them within the text can be a problem if you do not set it to the amount of spaces every one of us uses. Here is a short example of how it should look like:</p>
<div class="codebox"><pre>
{TAB}$mode{TAB}{TAB}= $request->variable('mode', '');
{TAB}$search_id{TAB}= $request->variable('search_id', '');</pre>
</div>
<p>If entered with tabs (replace the {TAB}) both equal signs need to be on the same column.</p>
<h3>Linefeeds:</h3>
<p>Ensure that your editor is saving files in the UNIX (LF) line ending format. This means that lines are terminated with a newline, not with Windows Line endings (CR/LF combo) as they are on Win32 or Classic Mac (CR) Line endings. Any decent editor should be able to do this, but it might not always be the default setting. Know your editor. If you want advice for an editor for your Operating System, just ask one of the developers. Some of them do their editing on Win32.</p>
<a name="fileheader"></a><h3>1.ii. File Layout</h3>
<h4>Standard header for new files:</h4>
<p>This template of the header must be included at the start of all phpBB files: </p>
<div class="codebox"><pre>
/**
*
* This file is part of the phpBB Forum Software package.
*
* @copyright (c) phpBB Limited <https://www.phpbb.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
* For full copyright and license information, please see
* the docs/CREDITS.txt file.
*
*/</pre>
</div>
<p>Please see the <a href="#locations">File Locations section</a> for the correct package name.</p>
<h4>PHP closing tags</h4>
<p>A file containg only PHP code should not end with the optional PHP closing tag <strong>?></strong> to avoid issues with whitespace following it.</p>
<h4>Newline at end of file</h4>
<p>All files should end in a newline so the last line does not appear as modified in diffs, when a line is appended to the file.</p>
<h4>Files containing inline code:</h4>
<p>For those files you have to put an empty comment directly after the header to prevent the documentor assigning the header to the first code element found.</p>
<div class="codebox"><pre>
/**
* {HEADER}
*/
/**
*/
{CODE}</pre>
</div>
<h4>Files containing only functions:</h4>
<p>Do not forget to comment the functions (especially the first function following the header). Each function should have at least a comment of what this function does. For more complex functions it is recommended to document the parameters too.</p>
<h4>Files containing only classes:</h4>
<p>Do not forget to comment the class. Classes need a separate @package definition, it is the same as the header package name. Apart from this special case the above statement for files containing only functions needs to be applied to classes and it's methods too.</p>
<h4>Code following the header but only functions/classes file:</h4>
<p>If this case is true, the best method to avoid documentation confusions is adding an ignore command, for example:</p>
<div class="codebox"><pre>
/**
* {HEADER}
*/
/**
* @ignore
*/
Small code snipped, mostly one or two defines or an if statement
/**
* {DOCUMENTATION}
*/
class ...</pre>
</div>
<a name="locations"></a><h3>1.iii. File Locations</h3>
<p>Functions used by more than one page should be placed in functions.php, functions specific to one page should be placed on that page (at the bottom) or within the relevant sections functions file. Some files in <code>/includes</code> are holding functions responsible for special sections, for example uploading files, displaying "things", user related functions and so forth.</p>
<p>The following packages are defined, and related new features/functions should be placed within the mentioned files/locations, as well as specifying the correct package name. The package names are bold within this list:</p>
<ul>
<li><strong>phpBB3</strong><br />Core files and all files not assigned to a separate package</li>
<li><strong>acm</strong><br /><code>/phpbb/cache</code><br />Cache System</li>
<li><strong>acp</strong><br /><code>/adm</code>, <code>/includes/acp</code>, <code>/includes/functions_admin.php</code><br />Administration Control Panel</li>
<li><strong>dbal</strong><br /><code>/phpbb/db</code>, <code>/includes/db</code><br />Database Abstraction Layer.
<ul>
<li><code>/phpbb/db/driver/</code><br />Database Abstraction Layer classes</li>
<li><code>/phpbb/db/migration/</code><br />Migrations are used for updating the database from one release to another</li>
</ul>
</li>
<li><strong>diff</strong><br /><code>/includes/diff</code><br />Diff Engine</li>
<li><strong>docs</strong><br /><code>/docs</code><br />phpBB Documentation</li>
<li><strong>images</strong><br /><code>/images</code><br />All global images not connected to styles</li>
<li><strong>install</strong><br /><code>/install</code><br />Installation System</li>
<li><strong>language</strong><br /><code>/language</code><br />All language files</li>
<li><strong>login</strong><br /><code>/phpbb/auth</code><br />Login Authentication Plugins</li>
<li><strong>VC</strong><br /><code>/includes/captcha</code><br />CAPTCHA</li>
<li><strong>mcp</strong><br /><code>mcp.php</code>, <code>/includes/mcp</code>, <code>report.php</code><br />Moderator Control Panel</li>
<li><strong>ucp</strong><br /><code>ucp.php</code>, <code>/includes/ucp</code><br />User Control Panel</li>
<li><strong>utf</strong><br /><code>/includes/utf</code><br />UTF8-related functions/classes</li>
<li><strong>search</strong><br /><code>/phpbb/search</code>, <code>search.php</code><br />Search System</li>
<li><strong>styles</strong><br /><code>/styles</code><br />phpBB Styles/Templates/Themes</li>
</ul>
<a name="constants"></a><h3>1.iv. Special Constants</h3>
<p>There are some special constants application developers are able to utilize to bend some of phpBB's internal functionality to suit their needs.</p>
<div class="codebox"><pre>
PHPBB_MSG_HANDLER (overwrite message handler)
PHPBB_DB_NEW_LINK (overwrite new_link parameter for sql_connect)
PHPBB_ROOT_PATH (overwrite $phpbb_root_path)
PHPBB_ADMIN_PATH (overwrite $phpbb_admin_path)
PHPBB_USE_BOARD_URL_PATH (use generate_board_url() for image paths instead of $phpbb_root_path)
PHPBB_DISABLE_ACP_EDITOR (disable ACP style editor for templates)
PHPBB_DISABLE_CONFIG_CHECK (disable ACP config.php writeable check)
PHPBB_ACM_MEMCACHE_PORT (overwrite memcached port, default is 11211)
PHPBB_ACM_MEMCACHE_COMPRESS (overwrite memcached compress setting, default is disabled)
PHPBB_ACM_MEMCACHE_HOST (overwrite memcached host name, default is localhost)
PHPBB_ACM_REDIS_HOST (overwrite redis host name, default is localhost)
PHPBB_ACM_REDIS_PORT (overwrite redis port, default is 6379)
PHPBB_ACM_REDIS_PASSWORD (overwrite redis password, default is empty)
PHPBB_ACM_REDIS_DB (overwrite redis default database)
PHPBB_QA (Set board to QA-Mode, which means the updater also checks for RC-releases)
</pre></div>
<h4>PHPBB_USE_BOARD_URL_PATH</h4>
<p>If the <code>PHPBB_USE_BOARD_URL_PATH</code> constant is set to true, phpBB uses generate_board_url() (this will return the boards url with the script path included) on all instances where web-accessible images are loaded. The exact locations are:</p>
<ul>
<li>/phpbb/user.php - \phpbb\user::img()</li>
<li>/includes/functions_content.php - smiley_text()</li>
</ul>
<p>Path locations for the following template variables are affected by this too:</p>
<ul>
<li>{T_ASSETS_PATH} - assets (non-style specific, static resources)</li>
<li>{T_THEME_PATH} - styles/xxx/theme</li>
<li>{T_TEMPLATE_PATH} - styles/xxx/template</li>
<li>{T_SUPER_TEMPLATE_PATH} - styles/xxx/template</li>
<li>{T_IMAGES_PATH} - images/</li>
<li>{T_SMILIES_PATH} - $config['smilies_path']/</li>
<li>{T_AVATAR_GALLERY_PATH} - $config['avatar_gallery_path']/</li>
<li>{T_ICONS_PATH} - $config['icons_path']/</li>
<li>{T_RANKS_PATH} - $config['ranks_path']/</li>
<li>{T_UPLOAD_PATH} - $config['upload_path']/</li>
<li>{T_STYLESHEET_LINK} - styles/xxx/theme/stylesheet.css</li>
<li>New template variable {BOARD_URL} for the board url + script path.</li>
</ul>
</div>
<div class="back2top"><a href="#wrap" class="top">Back to Top</a></div>
</div>
</div>
<hr />
<a name="code"></a><h2>2. Code Layout/Guidelines</h2>
<div class="paragraph">
<div class="inner">
<div class="content">
<p>Please note that these guidelines apply to all php, html, javascript and css files.</p>
<a name="namingvars"></a><h3>2.i. Variable/Function/Class Naming</h3>
<p>We will not be using any form of hungarian notation in our naming conventions. Many of us believe that hungarian naming is one of the primary code obfuscation techniques currently in use.</p>
<h4>Variable Names:</h4>
<p>In PHP, variable names should be in all lowercase, with words separated by an underscore, example:</p>
<div class="indent">
<p><code>$current_user</code> is right, but <code>$currentuser</code> and <code> $currentUser</code> are not.</p>
</div>
<p>In JavaScript, variable names should use camel case:</p>
<div class="indent">
<p><code>currentUser</code> is right, but <code>currentuser</code> and <code>current_user</code> are not.</p>
</div>
<p>Names should be descriptive, but concise. We don't want huge sentences as our variable names, but typing an extra couple of characters is always better than wondering what exactly a certain variable is for. </p>
<h4>Loop Indices:</h4>
<p>The <em>only</em> situation where a one-character variable name is allowed is when it's the index for some looping construct. In this case, the index of the outer loop should always be $i. If there's a loop inside that loop, its index should be $j, followed by $k, and so on. If the loop is being indexed by some already-existing variable with a meaningful name, this guideline does not apply, example:</p>
<div class="codebox"><pre>
for ($i = 0; $i < $outer_size; $i++)
{
for ($j = 0; $j < $inner_size; $j++)
{
foo($i, $j);
}
}</pre>
</div>
<h4>Function Names:</h4>
<p>Functions should also be named descriptively. We're not programming in C here, we don't want to write functions called things like "stristr()". Again, all lower-case names with words separated by a single underscore character in PHP, and camel caps in JavaScript. Function names should be prefixed with "phpbb_" and preferably have a verb in them somewhere. Good function names are <code>phpbb_print_login_status()</code>, <code>phpbb_get_user_data()</code>, etc. Constructor functions in JavaScript should begin with a capital letter.</p>
<h4>Function Arguments:</h4>
<p>Arguments are subject to the same guidelines as variable names. We don't want a bunch of functions like: <code>do_stuff($a, $b, $c)</code>. In most cases, we'd like to be able to tell how to use a function by just looking at its declaration. </p>
<h4>Class Names:</h4>
<p>Apart from following the rules for function names, all classes should meet the following conditions:</p>
<ul>
<li>Every class must be defined in a separate file.</li>
<li>The classes have to be located in a subdirectory of <code>phpbb/</code>.</li>
<li>Classnames must be namespaced with <code>\phpbb\</code> to avoid name clashes.</li>
<li>Class names/namespaces have to reflect the location of the file they are defined in. The namespace must be the directory in which the file is located. So the directory names must not contain any underscores, but the filename may.</li>
<li>Directories should typically be a singular noun (e.g. <code>dir</code> in the example below, not <code>dirs</code>.</li>
</ul>
<p>So given the following example directory structure you would result in the below listed lookups</p>
<div class="codebox"><pre>
phpbb/
class_name.php
dir/
class_name.php
subdir/
class_name.php</pre>
</div>
<div class="codebox"><pre>
\phpbb\class_name - phpbb/class_name.php
\phpbb\dir\class_name - phpbb/dir/class_name.php
\phpbb\dir\subdir\class_name - phpbb/dir/subdir/class_name.php</pre>
</div>
<h4>Summary:</h4>
<p>The basic philosophy here is to not hurt code clarity for the sake of laziness. This has to be balanced by a little bit of common sense, though; <code>phpbb_print_login_status_for_a_given_user()</code> goes too far, for example -- that function would be better named <code>phpbb_print_user_login_status()</code>, or just <code>phpbb_print_login_status()</code>.</p>
<h4>Special Namings: </h4>
<p>For all emoticons use the term <code>smiley</code> in singular and <code>smilies</code> in plural. For emails we use the term <code>email</code> (without dash between “e” and “m”).</p>
<a name="codelayout"></a><h3>2.ii. Code Layout</h3>
<h4>Always include the braces:</h4>
<p>This is another case of being too lazy to type 2 extra characters causing problems with code clarity. Even if the body of some construct is only one line long, do <em>not</em> drop the braces. Just don't, examples:</p>
<p class="bad">// These are all wrong. </p>
<div class="codebox"><pre>
if (condition) do_stuff();
if (condition)
do_stuff();
while (condition)
do_stuff();
for ($i = 0; $i < size; $i++)
do_stuff($i);</pre>
</div>
<p class="good">// These are all right. </p>
<div class="codebox"><pre>
if (condition)
{
do_stuff();
}
while (condition)
{
do_stuff();
}
for ($i = 0; $i < size; $i++)
{
do_stuff();
}</pre>
</div>
<h4>Where to put the braces:</h4>
<p>In PHP code, braces always go on their own line. The closing brace should also always be at the same column as the corresponding opening brace, examples:</p>
<div class="codebox"><pre>
if (condition)
{
while (condition2)
{
...
}
}
else
{
...
}
for ($i = 0; $i < $size; $i++)
{
...
}
while (condition)
{
...
}
function do_stuff()
{
...
}</pre>
</div>
<p>In JavaScript code, braces always go on the same line:</p>
<div class="codebox"><pre>
if (condition) {
while (condition2) {
...
}
} else {
...
}
for (var i = 0; i < size; i++) {
...
}
while (condition) {
...
}
function do_stuff() {
...
}</pre>
</div>
<h4>Use spaces between tokens:</h4>
<p>This is another simple, easy step that helps keep code readable without much effort. Whenever you write an assignment, expression, etc.. Always leave <em>one</em> space between the tokens. Basically, write code as if it was English. Put spaces between variable names and operators. Don't put spaces just after an opening bracket or before a closing bracket. Don't put spaces just before a comma or a semicolon. This is best shown with a few examples, examples:</p>
<p>// Each pair shows the wrong way followed by the right way. </p>
<div class="codebox"><pre>
$i=0;
$i = 0;
if($i<7) ...
if ($i < 7) ...
if ( ($i < 7)&&($j > 8) ) ...
if ($i < 7 && $j > 8) ...
do_stuff( $i, 'foo', $b );
do_stuff($i, 'foo', $b);
for($i=0; $i<$size; $i++) ...
for ($i = 0; $i < $size; $i++) ...
$i=($j < $size)?0:1;
$i = ($j < $size) ? 0 : 1;</pre>
</div>
<h4>Operator precedence:</h4>
<p>Do you know the exact precedence of all the operators in PHP? Neither do I. Don't guess. Always make it obvious by using brackets to force the precedence of an equation so you know what it does. Remember to not over-use this, as it may harden the readability. Basically, do not enclose single expressions. Examples:</p>
<p class="bad">// what's the result? who knows. </p>
<div class="codebox">
<pre>$bool = ($i < 7 && $j > 8 || $k == 4);</pre>
</div>
<p class="bad">// now you can be certain what I'm doing here.</p>
<div class="codebox">
<pre>$bool = (($i < 7) && (($j < 8) || ($k == 4)));</pre>
</div>
<p class="good">// But this one is even better, because it is easier on the eye but the intention is preserved</p>
<div class="codebox">
<pre>$bool = ($i < 7 && ($j < 8 || $k == 4));</pre>
</div>
<h4>Quoting strings:</h4>
<p>There are two different ways to quote strings in PHP - either with single quotes or with double quotes. The main difference is that the parser does variable interpolation in double-quoted strings, but not in single quoted strings. Because of this, you should <em>always</em> use single quotes <em>unless</em> you specifically need variable interpolation to be done on that string. This way, we can save the parser the trouble of parsing a bunch of strings where no interpolation needs to be done.</p>
<p>Also, if you are using a string variable as part of a function call, you do not need to enclose that variable in quotes. Again, this will just make unnecessary work for the parser. Note, however, that nearly all of the escape sequences that exist for double-quoted strings will not work with single-quoted strings. Be careful, and feel free to break this guideline if it's making your code easier to read, examples:</p>
<p class="bad">// wrong </p>
<div class="codebox"><pre>
$str = "This is a really long string with no variables for the parser to find.";
do_stuff("$str");</pre>
</div>
<p class="good">// right</p>
<div class="codebox"><pre>
$str = 'This is a really long string with no variables for the parser to find.';
do_stuff($str);</pre>
</div>
<p class="bad">// Sometimes single quotes are just not right</p>
<div class="codebox"><pre>
$post_url = $phpbb_root_path . 'posting.' . $phpEx . '?mode=' . $mode . '&amp;start=' . $start;</pre>
</div>
<p class="good">// Double quotes are sometimes needed to not overcrowd the line with concatenations.</p>
<div class="codebox"><pre>
$post_url = "{$phpbb_root_path}posting.$phpEx?mode=$mode&amp;start=$start";</pre>
</div>
<p>In SQL statements mixing single and double quotes is partly allowed (following the guidelines listed here about SQL formatting), else one should try to only use one method - mostly single quotes.</p>
<h4>Commas after every array element:</h4>
<p>If an array is defined with each element on its own line, you still have to modify the previous line to add a comma when appending a new element. PHP allows for trailing (useless) commas in array definitions. These should always be used so each element including the comma can be appended with a single line. In JavaScript, do not use the trailing comma, as it causes browsers to throw errors.</p>
<p class="bad">// wrong</p>
<div class="codebox"><pre>
$foo = array(
'bar' => 42,
'boo' => 23
);</pre>
</div>
<p class="good">// right </p>
<div class="codebox"><pre>
$foo = array(
'bar' => 42,
'boo' => 23,
);</pre>
</div>
<h4>Associative array keys:</h4>
<p>In PHP, it's legal to use a literal string as a key to an associative array without quoting that string. We don't want to do this -- the string should always be quoted to avoid confusion. Note that this is only when we're using a literal, not when we're using a variable, examples:</p>
<p class="bad">// wrong</p>
<div class="codebox">
<pre>$foo = $assoc_array[blah];</pre>
</div>
<p class="good">// right </p>
<div class="codebox">
<pre>$foo = $assoc_array['blah'];</pre>
</div>
<p class="bad">// wrong</p>
<div class="codebox">
<pre>$foo = $assoc_array["$var"];</pre>
</div>
<p class="good">// right </p>
<div class="codebox">
<pre>$foo = $assoc_array[$var];</pre>
</div>
<h4>Comments:</h4>
<p>Each complex function should be preceded by a comment that tells a programmer everything they need to know to use that function. The meaning of every parameter, the expected input, and the output are required as a minimal comment. The function's behaviour in error conditions (and what those error conditions are) should also be present - but mostly included within the comment about the output.<br /><br />Especially important to document are any assumptions the code makes, or preconditions for its proper operation. Any one of the developers should be able to look at any part of the application and figure out what's going on in a reasonable amount of time.<br /><br />Avoid using <code>/* */</code> comment blocks for one-line comments, <code>//</code> should be used for one/two-liners.</p>
<h4>Magic numbers:</h4>
<p>Don't use them. Use named constants for any literal value other than obvious special cases. Basically, it's ok to check if an array has 0 elements by using the literal 0. It's not ok to assign some special meaning to a number and then use it everywhere as a literal. This hurts readability AND maintainability. The constants <code>true</code> and <code>false</code> should be used in place of the literals 1 and 0 -- even though they have the same values (but not type!), it's more obvious what the actual logic is when you use the named constants. Typecast variables where it is needed, do not rely on the correct variable type (PHP is currently very loose on typecasting which can lead to security problems if a developer does not keep a very close eye on it).</p>
<h4>Shortcut operators:</h4>
<p>The only shortcut operators that cause readability problems are the shortcut increment <code>$i++</code> and decrement <code>$j--</code> operators. These operators should not be used as part of an expression. They can, however, be used on their own line. Using them in expressions is just not worth the headaches when debugging, examples:</p>
<p class="bad">// wrong </p>
<div class="codebox"><pre>
$array[++$i] = $j;
$array[$i++] = $k;</pre>
</div>
<p class="good">// right </p>
<div class="codebox"><pre>
$i++;
$array[$i] = $j;
$array[$i] = $k;
$i++;</pre>
</div>
<h4>Inline conditionals:</h4>
<p>Inline conditionals should only be used to do very simple things. Preferably, they will only be used to do assignments, and not for function calls or anything complex at all. They can be harmful to readability if used incorrectly, so don't fall in love with saving typing by using them, examples:</p>
<p class="bad">// Bad place to use them</p>
<div class="codebox"><pre>
($i < $size && $j > $size) ? do_stuff($foo) : do_stuff($bar);</pre>
</div>
<p class="good">// OK place to use them </p>
<div class="codebox"><pre>
$min = ($i < $j) ? $i : $j;</pre>
</div>
<h4>Don't use uninitialized variables.</h4>
<p>For phpBB3, we intend to use a higher level of run-time error reporting. This will mean that the use of an uninitialized variable will be reported as a warning. These warnings can be avoided by using the built-in isset() function to check whether a variable has been set - but preferably the variable is always existing. For checking if an array has a key set this can come in handy though, examples:</p>
<p class="bad">// Wrong </p>
<div class="codebox">
<pre>if ($forum) ...</pre>
</div>
<p class="good">// Right </p>
<div class="codebox">
<pre>if (isset($forum)) ...</pre></div>
<p class="good">// Also possible</p>
<div class="codebox">
<pre>if (isset($forum) && $forum == 5)</pre>
</div>
<p>The <code>empty()</code> function is useful if you want to check if a variable is not set or being empty (an empty string, 0 as an integer or string, NULL, false, an empty array or a variable declared, but without a value in a class). Therefore empty should be used in favor of <code>isset($array) && count($array) > 0</code> - this can be written in a shorter way as <code>!empty($array)</code>.</p>
<h4>Switch statements:</h4>
<p>Switch/case code blocks can get a bit long sometimes. To have some level of notice and being in-line with the opening/closing brace requirement (where they are on the same line for better readability), this also applies to switch/case code blocks and the breaks. An example:</p>
<p class="bad">// Wrong </p>
<div class="codebox"><pre>
switch ($mode)
{
case 'mode1':
// I am doing something here
break;
case 'mode2':
// I am doing something completely different here
break;
}</pre>
</div>
<p class="good">// Good </p>
<div class="codebox"><pre>
switch ($mode)
{
case 'mode1':
// I am doing something here
break;
case 'mode2':
// I am doing something completely different here
break;
default:
// Always assume that a case was not caught
break;
}</pre>
</div>
<p class="good">// Also good, if you have more code between the case and the break </p>
<div class="codebox"><pre>
switch ($mode)
{
case 'mode1':
// I am doing something here
break;
case 'mode2':
// I am doing something completely different here
break;
default:
// Always assume that a case was not caught
break;
}</pre>
</div>
<p>Even if the break for the default case is not needed, it is sometimes better to include it just for readability and completeness.</p>
<p>If no break is intended, please add a comment instead. An example:</p>
<p class="good">// Example with no break </p>
<div class="codebox"><pre>
switch ($mode)
{
case 'mode1':
// I am doing something here
// no break here
case 'mode2':
// I am doing something completely different here
break;
default:
// Always assume that a case was not caught
break;
}</pre>
</div>
<h4>Class Members</h4>
<p>Use the explicit visibility qualifiers <code>public</code>, <code>private</code> and <code>protected</code> for all properties instead of <code>var</code>.
<p>Place the <code>static</code> qualifier before the visibility qualifiers.</p>
<p class="bad">//Wrong </p>
<div class="codebox"><pre>
var $x;
private static function f()</pre>
</div>
<p class="good">// Right </p>
<div class="codebox"><pre>
public $x;
static private function f()</pre>
</div>
<h4>Constants</h4>
<p>Prefer class constants over global constants created with <code>define()</code>.</p>
<a name="sql"></a><h3>2.iii. SQL/SQL Layout</h3>
<h4>Common SQL Guidelines: </h4>
<p>All SQL should be cross-DB compatible, if DB specific SQL is used alternatives must be provided which work on all supported DB's (MySQL3/4/5, MSSQL (7.0 and 2000), PostgreSQL (8.3+), SQLite, Oracle8, ODBC (generalised if possible)).</p>
<p>All SQL commands should utilise the DataBase Abstraction Layer (DBAL)</p>
<h4>SQL code layout:</h4>
<p>SQL Statements are often unreadable without some formatting, since they tend to be big at times. Though the formatting of sql statements adds a lot to the readability of code. SQL statements should be formatted in the following way, basically writing keywords: </p>
<div class="codebox"><pre>
$sql = 'SELECT *
<-one tab->FROM ' . SOME_TABLE . '
<-one tab->WHERE a = 1
<-two tabs->AND (b = 2
<-three tabs->OR b = 3)
<-one tab->ORDER BY b';</pre>
</div>
<p>Here the example with the tabs applied:</p>
<div class="codebox"><pre>
$sql = 'SELECT *
FROM ' . SOME_TABLE . '
WHERE a = 1
AND (b = 2
OR b = 3)
ORDER BY b';</pre>
</div>
<h4>SQL Quotes: </h4>
<p>Use double quotes where applicable. (The variables in these examples are typecasted to integers beforehand.) Examples: </p>
<p class="bad">// These are wrong.</p>
<div class="codebox"><pre>
"UPDATE " . SOME_TABLE . " SET something = something_else WHERE a = $b";
'UPDATE ' . SOME_TABLE . ' SET something = ' . $user_id . ' WHERE a = ' . $something;</pre>
</div>
<p class="good">// These are right. </p>
<div class="codebox"><pre>
'UPDATE ' . SOME_TABLE . " SET something = something_else WHERE a = $b";
'UPDATE ' . SOME_TABLE . " SET something = $user_id WHERE a = $something";</pre>
</div>
<p>In other words use single quotes where no variable substitution is required or where the variable involved shouldn't appear within double quotes. Otherwise use double quotes.</p>
<h4>Avoid DB specific SQL: </h4>
<p>The "not equals operator", as defined by the SQL:2003 standard, is "<>"</p>
<p class="bad">// This is wrong.</p>
<div class="codebox"><pre>
$sql = 'SELECT *
FROM ' . SOME_TABLE . '
WHERE a != 2';</pre>
</div>
<p class="good">// This is right. </p>
<div class="codebox"><pre>
$sql = 'SELECT *
FROM ' . SOME_TABLE . '
WHERE a <> 2';</pre>
</div>
<h4>Common DBAL methods: </h4>
<h4>sql_escape():</h4>
<p>Always use <code>$db->sql_escape()</code> if you need to check for a string within an SQL statement (even if you are sure the variable cannot contain single quotes - never trust your input), for example:</p>
<div class="codebox"><pre>
$sql = 'SELECT *
FROM ' . SOME_TABLE . "
WHERE username = '" . $db->sql_escape($username) . "'";</pre>
</div>
<h4>sql_query_limit():</h4>
<p>We do not add limit statements to the sql query, but instead use <code>$db->sql_query_limit()</code>. You basically pass the query, the total number of lines to retrieve and the offset.</p>
<p><strong>Note: </strong> Since Oracle handles limits differently and because of how we implemented this handling you need to take special care if you use <code>sql_query_limit</code> with an sql query retrieving data from more than one table.</p>
<p>Make sure when using something like "SELECT x.*, y.jars" that there is not a column named jars in x; make sure that there is no overlap between an implicit column and the explicit columns.</p>
<h4>sql_build_array():</h4>
<p>If you need to UPDATE or INSERT data, make use of the <code>$db->sql_build_array()</code> function. This function already escapes strings and checks other types, so there is no need to do this here. The data to be inserted should go into an array - <code>$sql_ary</code> - or directly within the statement if one or two variables needs to be inserted/updated. An example of an insert statement would be:</p>
<div class="codebox"><pre>
$sql_ary = array(
'somedata' => $my_string,
'otherdata' => $an_int,
'moredata' => $another_int,
);
$db->sql_query('INSERT INTO ' . SOME_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));</pre>
</div>
<p>To complete the example, this is how an update statement would look like:</p>
<div class="codebox"><pre>
$sql_ary = array(
'somedata' => $my_string,
'otherdata' => $an_int,
'moredata' => $another_int,
);
$sql = 'UPDATE ' . SOME_TABLE . '
SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
WHERE user_id = ' . (int) $user_id;
$db->sql_query($sql);</pre>
</div>
<p>The <code>$db->sql_build_array()</code> function supports the following modes: <code>INSERT</code> (example above), <code>INSERT_SELECT</code> (building query for <code>INSERT INTO table (...) SELECT value, column ...</code> statements), <code>UPDATE</code> (example above) and <code>SELECT</code> (for building WHERE statement [AND logic]).</p>
<h4>sql_multi_insert():</h4>
<p>If you want to insert multiple statements at once, please use the separate <code>sql_multi_insert()</code> method. An example:</p>
<div class="codebox"><pre>
$sql_ary = array();
$sql_ary[] = array(
'somedata' => $my_string_1,
'otherdata' => $an_int_1,
'moredata' => $another_int_1,
);
$sql_ary[] = array(
'somedata' => $my_string_2,
'otherdata' => $an_int_2,
'moredata' => $another_int_2,
);
$db->sql_multi_insert(SOME_TABLE, $sql_ary);</pre>
</div>
<h4>sql_in_set():</h4>
<p>The <code>$db->sql_in_set()</code> function should be used for building <code>IN ()</code> and <code>NOT IN ()</code> constructs. Since (specifically) MySQL tend to be faster if for one value to be compared the <code>=</code> and <code><></code> operator is used, we let the DBAL decide what to do. A typical example of doing a positive match against a number of values would be:</p>
<div class="codebox"><pre>
$sql = 'SELECT *
FROM ' . FORUMS_TABLE . '
WHERE ' . $db->sql_in_set('forum_id', $forum_ids);
$db->sql_query($sql);</pre>
</div>
<p>Based on the number of values in $forum_ids, the query can look differently.</p>
<p class="good">// SQL Statement if $forum_ids = array(1, 2, 3);</p>
<div class="codebox"><pre>
SELECT FROM phpbb_forums WHERE forum_id IN (1, 2, 3)</pre>
</div>
<p class="good">// SQL Statement if $forum_ids = array(1) or $forum_ids = 1</p>
<div class="codebox"><pre>
SELECT FROM phpbb_forums WHERE forum_id = 1</pre>
</div>
<p>Of course the same is possible for doing a negative match against a number of values:</p>
<div class="codebox"><pre>
$sql = 'SELECT *
FROM ' . FORUMS_TABLE . '
WHERE ' . $db->sql_in_set('forum_id', $forum_ids, <strong>true</strong>);
$db->sql_query($sql);</pre>
</div>
<p>Based on the number of values in $forum_ids, the query can look differently here too.</p>
<p class="good">// SQL Statement if $forum_ids = array(1, 2, 3);</p>
<div class="codebox"><pre>
SELECT FROM phpbb_forums WHERE forum_id <strong>NOT</strong> IN (1, 2, 3)</pre>
</div>
<p class="good">// SQL Statement if $forum_ids = array(1) or $forum_ids = 1</p>
<div class="codebox"><pre>
SELECT FROM phpbb_forums WHERE forum_id <strong><></strong> 1</pre>
</div>
<p>If the given array is empty, an error will be produced.</p>
<h4>sql_build_query():</h4>
<p>The <code>$db->sql_build_query()</code> function is responsible for building sql statements for SELECT and SELECT DISTINCT queries if you need to JOIN on more than one table or retrieve data from more than one table while doing a JOIN. This needs to be used to make sure the resulting statement is working on all supported db's. Instead of explaining every possible combination, I will give a short example:</p>
<div class="codebox"><pre>
$sql_array = array(
'SELECT' => 'f.*, ft.mark_time',
'FROM' => array(
FORUMS_WATCH_TABLE => 'fw',
FORUMS_TABLE => 'f',
),
'LEFT_JOIN' => array(
array(
'FROM' => array(FORUMS_TRACK_TABLE => 'ft'),
'ON' => 'ft.user_id = ' . $user->data['user_id'] . ' AND ft.forum_id = f.forum_id',
),
),
'WHERE' => 'fw.user_id = ' . $user->data['user_id'] . '
AND f.forum_id = fw.forum_id',
'ORDER_BY' => 'left_id',
);
$sql = $db->sql_build_query('SELECT', $sql_array);</pre>
</div>
<p>The possible first parameter for sql_build_query() is SELECT or SELECT_DISTINCT. As you can see, the logic is pretty self-explaining. For the LEFT_JOIN key, just add another array if you want to join on to tables for example. The added benefit of using this construct is that you are able to easily build the query statement based on conditions - for example the above LEFT_JOIN is only necessary if server side topic tracking is enabled; a slight adjustement would be:</p>
<div class="codebox"><pre>
$sql_array = array(
'SELECT' => 'f.*',
'FROM' => array(
FORUMS_WATCH_TABLE => 'fw',
FORUMS_TABLE => 'f',
),
'WHERE' => 'fw.user_id = ' . $user->data['user_id'] . '
AND f.forum_id = fw.forum_id',
'ORDER_BY' => 'left_id',
);
if ($config['load_db_lastread'])
{
$sql_array['LEFT_JOIN'] = array(
array(
'FROM' => array(FORUMS_TRACK_TABLE => 'ft'),
'ON' => 'ft.user_id = ' . $user->data['user_id'] . ' AND ft.forum_id = f.forum_id',
),
);
$sql_array['SELECT'] .= ', ft.mark_time ';
}
else
{
// Here we read the cookie data
}
$sql = $db->sql_build_query('SELECT', $sql_array);</pre>
</div>
<a name="optimizing"></a><h3>2.iv. Optimizations</h3>
<h4>Operations in loop definition: </h4>
<p>Always try to optimize your loops if operations are going on at the comparing part, since this part is executed every time the loop is parsed through. For assignments a descriptive name should be chosen. Example:</p>
<p class="bad">// On every iteration the count function is called</p>
<div class="codebox"><pre>
for ($i = 0; $i < count($post_data); $i++)
{
do_something();