mirrored from git://git.moodle.org/moodle.git
-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
coding.html
233 lines (233 loc) · 15.3 KB
/
coding.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
<html>
<head>
<title>Moodle Docs: Coding Guidelines</title>
<link rel="stylesheet" href="docstyles.css" type="TEXT/CSS">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF">
<h1>Manual de Estilo del Código</h1>
<p class="normaltext">Cualquier proyecto colaborativo necesita que la consistencia
y la estabilidad sean fuertes.</p>
<p class="normaltext">Este manual de estilo ha sido escrito para conseguir que
todo el código de Moodle cumpla estas características. Es cierto
que la parte más antigua del código no cumple lo aquí especificado
en algunos casos, pero esto será solucionado en breve. Todo el código
nuevo definitivamente deberá adherirse a estos estándares de la
forma más exacta posible.</p>
<h2>Reglas Generales</h2>
<ol class="normaltext">
<li class="spaced">Todos los archivos con código deberían utilizar la extensión
.php.</li>
<li class="spaced">Todas las plantillas deberían utilizar la extensión .html.</li>
<li class="spaced">Todos los archivos de texto deberían utilizar el formato
de texto Unix (la mayoría de los editores de texto tienen esto como una opción).</li>
<li class="spaced">Todas las etiquetas php deben ser 'completas' como <font color="#339900"><?php
?></font> ... no 'reducidas' como <font color="#339900"><?
?></font>.
</li>
<li class="spaced">Todos los avisos de copyright deben ser mantenidos. Puedes
incluir los tuyos propios si resulta necesario.</li>
<li class="spaced">Todos los archivos deben incluir el archivo principal config.php.</li>
<li class="spaced">Cada archivo debería comprobar que el usuario está autenticado
correctamente, utilizando las funciones require_login() y
isadmin(),
isteacher(),
iscreator()
o isstudent().</li>
<li class="spaced">Todos los accesos a la base de datos deberían utilizar
las funciones definidas en lib/datalib.php cuando sea posible - esto permite
la compatibilidad con un gran número de bases de datos. Deberías
encontrar que prácticamente todo es posible utilizando estas funciones.
Si quieres escribir código SQL entonces deberás comprobar que:
funciona en cualquier plataforma; restringido a funciones específicas
de tu código (normalmente un archivo lib.php); y claramente comentado.</li>
<li class="spaced">No crees o utilices variables globales distintas de las
estándar $CFG, $SESSION, $THEME y $USER.</li>
<li class="spaced">Todas las variables deberían ser inicializadas o, al menos,
comprobada su existencia utilizando isset()
o empty()
antes de ser utilizadas.</li>
<li class="spaced">Todas las cadenas deberían ser traducibles - crea nuevos
textos en los archivos "lang/es" files
con palabras reducidas en inglés y su traducción completa al Español y recupéralas
en tu código utilizando las funciones get_string() or print_string().</li>
<li class="spaced">Todos los archivos de ayuda deberían ser traducibles - crea
nuevos textos en el directorio "es/help" y llámalos utilizando
la función helpbutton().</li>
<li class="spaced">La información que llega desde el navegador (enviada
con los métodos GET o POST) automáticamente tiene las "magic_quotes"
aplicadas (sin importar la configuración de PHP) por lo que puedes
insertarla con total seguridad en la base de datos. El resto de la información(obtenida
desde los archivos, o desde la base de datos) debe ser escapada con la función
<font color="#339900">addslashes()</font> antes de insertarla en la base de
datos.</li>
</ol>
<p> </p>
<h2>Estilo del Código</h2>
<p class="normaltext">Comprendo que puede ser un poco frustrante modificar tu
estilo de programación si has trabajado en otras cosas, pero compara
esa frustración con la frustración de toda la gente que intente,
más adelante, encontrar el sentido del código de Moodle si es
una mezcla de estilos. Obviamente, hay muchos puntos a favor y en contra de
cada estilo que la gente utiliza, pero el que se detalla aquí es el que
deberás utilizar.</p>
<ol class="normaltext">
<li class="spaced"><strong>El sangrado</strong> del texto debe ser siempre
de 4 espacios. No utilices los tabuladosres NUNCA.</li>
<li class="spaced"><strong>Los nombres de las variables</strong> tienen que
ser siempre fáciles de leer, procurando que sean palabras en minúsculas con
significado en Inglés. Si realmente necesitas más de una palabra, ponlas
juntas, pero procura mantenerlas tan breves como sea posible. Utiliza nombres
en plural para las matrices de objetos.
<p class="examplecode"><font color="#006600">BIEN</font><font color="#006600">:
$quiz<br>
BIEN</font><font color="#006600"></font><font color="#006600">: $errorstring<br>
BIEN</font><font color="#006600"></font><font color="#006600">: $assignments
(for an array of objects)<br>
BIEN</font><font color="#006600"></font><font color="#006600">: $i (but
only in little loops)<br>
<br />
MAL: $Quiz <br>
MAL: $aReallyLongVariableNameWithoutAGoodReason<br>
MAL: $error_string</font></p>
</li>
<li class="spaced"><strong>Las constantes</strong> tienen que definirse siempre
en mayúsculas, y empezar siempre por el nombre del módulo al que pertenecen.
Deberían tener las palabras separadas por guiones bajos.
<p class="examplecode"><font color="#006600">define("FORUM_MODE_FLATOLDEST",
1);</font></p>
</li>
<li class="spaced"><strong>Los nombres de las funciones</strong> tienen que
ser palabras sencillas en minúsculas y en Inglés, y empezar
con el nombre del módulo al que pertenecen para evitar conflictos entre
módulos. Las palabras deberían separarse por guiones bajos.
Los parámentros, si es posible, tendrán valores por defecto.
Fíjate en que no haya espacio entre el nombre de la función
y lo siguiente (paréntesis).<br>
<p class="examplecode"> <font color="#007700">function </font><font color="#0000BB">forum_set_display_mode</font><font color="#007700">(</font><font color="#0000BB">$mode</font><font color="#007700">=</font><font color="#0000BB">0</font><font color="#007700">)
{<br />
global </font><font color="#0000BB">$USER</font><font color="#007700">,
</font><font color="#0000BB">$CFG</font><font color="#007700">;<br />
<br />
if (</font><font color="#0000BB">$mode</font><font color="#007700">)
{<br />
</font><font color="#0000BB">$USER</font><font color="#007700">-></font><font color="#0000BB">mode
</font><font color="#007700">= </font><font color="#0000BB">$mode</font><font color="#007700">;<br />
} else if (empty(</font><font color="#0000BB">$USER</font><font color="#007700">-></font><font color="#0000BB">mode</font><font color="#007700">))
{<br />
</font><font color="#0000BB">$USER</font><font color="#007700">-></font><font color="#0000BB">mode
</font><font color="#007700">= </font><font color="#0000BB">$CFG</font><font color="#007700">-></font><font color="#0000BB">forum_displaymode</font><font color="#007700">;<br />
}<br />
}</font></p>
</li>
<li class="spaced"><strong>Los bloques de código</strong> siempre deben
estar encerrados por llaves (incluso si solo constan de una línea).
Moodle utiliza este estilo:
<p class="examplecode"> <font color="#006600">if (</font><font color="#0000CC">$quiz</font><font color="#006600">-></font><font color="#0000CC">attempts</font><font color="#006600">)
{<br />
if (</font><font color="#0000CC">$numattempts </font><font color="#006600">>
</font><font color="#0000CC">$quiz</font><font color="#006600">-></font><font color="#0000CC">attempts</font><font color="#006600">)
{<br />
</font><font color="#0000CC">error</font><font color="#006600">(</font><font color="#0000BB">$strtoomanyattempts</font><font color="#006600">,
</font><font color="#CC0000">"view.php?id=$cm</font><font color="#006600">-></font><font color="#CC0000">id"</font><font color="#006600">);<br />
}<br />
}</font></p>
</li>
<li class="spaced"><strong>Las cadenas </strong> tienen que ser definidas utilizando
comillas simples siempre que sea posible, para obtener un mejor rendimiento.<br>
<p class="examplecode"> <font color="#006600">$var = 'some text without any
variables';<br>
$var = "with special characters like a new line \n";<br>
$var = 'a very, very long string with a '.$single.' variable in it';<br>
$var = "some $text with $many variables $within it"; </font></p>
</li>
<li class="spaced"><strong>Los comentarios</strong> utilizarán dos o tres barras
y estarán alineados con el código
<p class="examplecode"><font color="#006600">function </font><font color="#0000BB">forum_get_ratings_mean</font><font color="#007700">(</font><font color="#0000BB">$postid</font><font color="#007700">,
</font><font color="#0000BB">$scale</font><font color="#007700">, </font><font color="#0000BB">$ratings</font><font color="#007700">=</font><font color="#0000BB">NULL</font><font color="#007700">)
{<br />
</font><font color="#FF8000">/// Return the mean rating of a post given
to the current user by others.<br />
/// Scale is an array of possible ratings in the scale<br />
/// Ratings is an optional simple array of actual ratings (just integers)<br />
<br />
</font><font color="#007700">if (!</font><font color="#0000BB">$ratings</font><font color="#007700">)
{<br />
</font><font color="#0000BB">$ratings
</font><font color="#007700">= array(); </font><font color="#FF8000">//
Initialize the empty array</font><font color="#007700"><br />
if (</font><font color="#0000BB">$rates
</font><font color="#007700">= </font><font color="#0000BB">get_records</font><font color="#007700">(</font><font color="#DD0000">"forum_ratings"</font><font color="#007700">,
</font><font color="#DD0000">"post"</font><font color="#007700">, </font><font color="#0000BB">$postid</font><font color="#007700">))
{<br>
</font><font color="#FF8000">//
Process each rating in turn</font><font color="#007700"><br />
foreach
(</font><font color="#0000BB">$rates </font><font color="#007700">as </font><font color="#0000BB">$rate</font><font color="#007700">)
{</font> <br>
....etc </p>
</li>
<li class="spaced"><strong>El espacio en blanco</strong> se puede utilizar
con bastante libertad - no te preocupes por separar las cosas un poco para
ganar en claridad. Generalmente, debería haber un espacio entre llaves y
líneas normales y ninguno entre llaves y variables o funciones:<br>
<p class="examplecode"> <font color="#007700">foreach (</font><font color="#0000BB">$objects
</font><font color="#007700">as </font><font color="#0000BB">$key </font><font color="#007700">=></font><font color="#0000BB">
$thing</font><font color="#007700">)</font><font color="#006600"> {<br>
</font><font color="#007700"> </font><font color="#0000BB">process($thing);</font><font color="#006600">
<br>
} <br>
<br>
</font><font color="#007700">if (</font><font color="#0000BB">$x </font><font color="#007700">==
</font><font color="#0000BB">$y</font><font color="#007700">)</font><font color="#006600">
{<br>
</font><font color="#007700"> </font><font color="#0000BB">$a
</font><font color="#007700">= </font><font color="#0000BB">$b</font><font color="#007700">;</font><font color="#006600"><br>
} else if (</font><font color="#0000BB">$x </font><font color="#007700">==
</font><font color="#0000BB">$z</font><font color="#006600">) {<br>
</font><font color="#007700"> </font><font color="#0000BB">$a
</font><font color="#007700">= </font><font color="#0000BB">$c</font><font color="#007700">;</font><font color="#006600"><br>
} else {<br>
</font><font color="#007700"> </font><font color="#0000BB">$a
</font><font color="#007700">= </font><font color="#0000BB">$d</font><font color="#007700">;</font><font color="#006600"><br>
} </font></p>
</li>
</ol>
<p> </p>
<h2>Estructuras de la base de datos</h2>
<ol class="normaltext">
<li class="spaced">Cada tabla debe tener un campo autonumérico <strong>id</strong> (INT10)
como clave primaria.</li>
<li class="spaced">La tabla principal que contiene instancias de cada módulo
debe tener el mismo nombre que el módulo y contener, por lo menos, los siguientes
campos:
<ul>
<li><strong>id</strong> - descrito arriba</li>
<li><strong>course</strong> - el identificador del curso al que la instancia
pertenece</li>
<li><strong>name</strong> - el nombre completo de la instancia</li>
</ul>
</li>
<li class="spaced">El resto de las tablas asociadas con un módulo que
contiene información sobre 'cosas', deberían ser llamandas <strong>modulo_cosas
</strong>(fíjate en el plural!).</li>
<li class="spaced">Los nombres de los campos (columnas) deberían ser sencillos
y cortos, siguiendo las mismas reglas que los nombres de las variables.</li>
<li class="spaced">Cuando sea posible, las columnas que contengan una referencia
al campo id de otra tabla
(por ejemplo, <strong>modulo</strong>)
debería ser llamado <strong>moduloid</strong>.
(fíjate que esta norma es nueva y no es seguida por algunas tablas antiguas).</li>
<li class="spaced">Los campos booleanos serán implementados como enteros cortos
(por ejemplo, INT4) con los valores 0 o 1,
para permitir la futura expansión de los valores si fuera necesario.</li>
<li class="spaced">La mayoría de las tablas tienen que tener un campo <strong>timemodified</strong> (INT10)
que será actualizado con la fecha actual (timestamp de UNIX) obtenida con
la función <strong>time</strong>()
de PHP.</li>
</ol>
<hr>
<p align="CENTER"><font size="1"><a href="." target="_top">Documentación de Moodle</a></font></p>
<p align="CENTER"><font size="1">Version: $Id$</font></p>
</body>
</html>