Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like DbPDO often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use DbPDO, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
33 | abstract class DbPDO extends DbBase implements DbPDOInterface |
||
34 | { |
||
35 | |||
36 | /** |
||
37 | * Instancia PDO |
||
38 | * |
||
39 | * @var PDO |
||
40 | */ |
||
41 | protected $pdo; |
||
42 | /** |
||
43 | * Último Resultado de una Query |
||
44 | * |
||
45 | * @var PDOStament |
||
46 | */ |
||
47 | public $pdo_statement; |
||
48 | /** |
||
49 | * Última sentencia SQL enviada |
||
50 | * |
||
51 | * @var string |
||
52 | */ |
||
53 | protected $last_query; |
||
54 | /** |
||
55 | * Último error generado |
||
56 | * |
||
57 | * @var string |
||
58 | */ |
||
59 | protected $last_error; |
||
60 | /** |
||
61 | * Número de filas afectadas |
||
62 | */ |
||
63 | protected $affected_rows; |
||
64 | /** |
||
65 | * Nombre del Driver RBDM |
||
66 | */ |
||
67 | protected $db_rbdm; |
||
68 | |||
69 | /** |
||
70 | * Resultado de Array Asociativo |
||
71 | * |
||
72 | */ |
||
73 | const DB_ASSOC = PDO::FETCH_ASSOC; |
||
74 | |||
75 | /** |
||
76 | * Resultado de Array Asociativo y Númerico |
||
77 | * |
||
78 | */ |
||
79 | const DB_BOTH = PDO::FETCH_BOTH; |
||
80 | |||
81 | /** |
||
82 | * Resultado de Array Númerico |
||
83 | * |
||
84 | */ |
||
85 | const DB_NUM = PDO::FETCH_NUM; |
||
86 | |||
87 | /** |
||
88 | * Hace una conexión a la base de datos de MySQL |
||
89 | * |
||
90 | * @param array $config |
||
91 | * @return bool |
||
92 | */ |
||
93 | public function connect($config) |
||
94 | { |
||
95 | |||
96 | if (!extension_loaded('pdo')) { |
||
97 | throw new KumbiaException('Debe cargar la extensión de PHP llamada php_pdo'); |
||
98 | } |
||
99 | |||
100 | try { |
||
101 | $this->pdo = new PDO($config['type'] . ":" . $config['dsn'], $config['username'], $config['password']); |
||
102 | if (!$this->pdo) { |
||
103 | throw new KumbiaException("No se pudo realizar la conexion con $this->db_rbdm"); |
||
104 | } |
||
105 | if ($this->db_rbdm != 'odbc') { |
||
106 | $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); |
||
107 | $this->pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER); |
||
108 | $this->pdo->setAttribute(PDO::ATTR_CURSOR, PDO::CURSOR_FWDONLY); |
||
109 | } |
||
110 | //Selecciona charset |
||
111 | if ($config['type'] == 'mysql' && isset($config['charset'])) { |
||
112 | $this->pdo->exec('set character set ' . $config['charset']); |
||
113 | } |
||
114 | $this->initialize(); |
||
115 | return true; |
||
116 | } catch (PDOException $e) { |
||
117 | throw new KumbiaException($this->error($e->getMessage())); |
||
118 | } |
||
119 | } |
||
120 | |||
121 | /** |
||
122 | * Efectua operaciones SQL sobre la base de datos |
||
123 | * |
||
124 | * @param string $sql_query |
||
125 | * @return resource or false |
||
126 | */ |
||
127 | public function query($sql_query) |
||
128 | { |
||
129 | $this->debug($sql_query); |
||
130 | if ($this->logger) { |
||
131 | Logger::debug($sql_query); |
||
132 | } |
||
133 | if (!$this->pdo) { |
||
134 | throw new KumbiaException('No hay conexión para realizar esta acción'); |
||
135 | } |
||
136 | $this->last_query = $sql_query; |
||
137 | $this->pdo_statement = null; |
||
138 | try { |
||
139 | if ($pdo_statement = $this->pdo->query($sql_query)) { |
||
140 | $this->pdo_statement = $pdo_statement; |
||
141 | return $pdo_statement; |
||
142 | } else { |
||
143 | return false; |
||
144 | } |
||
145 | } catch (PDOException $e) { |
||
146 | throw new KumbiaException($this->error($e->getMessage() . " al ejecutar <em>\"$sql_query\"</em>")); |
||
147 | } |
||
148 | } |
||
149 | |||
150 | /** |
||
151 | * Efectua operaciones SQL sobre la base de datos y devuelve el numero de filas afectadas |
||
152 | * |
||
153 | * @param string $sql_query |
||
154 | * @return integer |
||
155 | */ |
||
156 | public function exec($sql_query) |
||
157 | { |
||
158 | $this->debug(">" . $sql_query); |
||
159 | if ($this->logger) { |
||
160 | Logger::debug($sql_query); |
||
161 | } |
||
162 | if (!$this->pdo) { |
||
163 | throw new KumbiaException('No hay conexión para realizar esta acción'); |
||
164 | } |
||
165 | $this->last_query = $sql_query; |
||
166 | $this->pdo_statement = null; |
||
167 | try { |
||
168 | $result = $this->pdo->exec($sql_query); |
||
169 | $this->affected_rows = $result; |
||
170 | if ($result === false) { |
||
171 | throw new KumbiaException($this->error(" al ejecutar <em>\"$sql_query\"</em>")); |
||
172 | } |
||
173 | return $result; |
||
174 | } catch (PDOException $e) { |
||
175 | throw new KumbiaException($this->error(" al ejecutar <em>\"$sql_query\"</em>")); |
||
176 | } |
||
177 | } |
||
178 | |||
179 | /** |
||
180 | * Cierra la Conexión al Motor de Base de datos |
||
181 | * |
||
182 | */ |
||
183 | public function close() |
||
184 | { |
||
185 | if ($this->pdo) { |
||
186 | unset($this->pdo); |
||
187 | return true; |
||
188 | } |
||
189 | return false; |
||
190 | } |
||
191 | |||
192 | /** |
||
193 | * Devuelve fila por fila el contenido de un select |
||
194 | * |
||
195 | * @param resource $pdo_statement |
||
196 | * @param int $opt |
||
197 | * @return array |
||
198 | */ |
||
199 | public function fetch_array($pdo_statement=NULL, $opt='') |
||
200 | { |
||
201 | if ($opt === '') { |
||
202 | $opt = self::DB_BOTH; |
||
203 | } |
||
204 | if (!$this->pdo) { |
||
205 | throw new KumbiaException('No hay conexión para realizar esta acción'); |
||
206 | } |
||
207 | if (!$pdo_statement) { |
||
208 | $pdo_statement = $this->pdo_statement; |
||
209 | if (!$pdo_statement) { |
||
210 | return false; |
||
211 | } |
||
212 | } |
||
213 | try { |
||
214 | $pdo_statement->setFetchMode($opt); |
||
215 | return $pdo_statement->fetch(); |
||
216 | } catch (PDOException $e) { |
||
217 | throw new KumbiaException($this->error($e->getMessage())); |
||
218 | } |
||
219 | } |
||
220 | |||
221 | /** |
||
222 | * Constructor de la Clase |
||
223 | * |
||
224 | * @param array $config |
||
225 | */ |
||
226 | public function __construct($config) |
||
227 | { |
||
228 | $this->connect($config); |
||
229 | } |
||
230 | |||
231 | /** |
||
232 | * Devuelve el numero de filas de un select (No soportado en PDO) |
||
233 | * |
||
234 | * @param PDOStatement $pdo_statement |
||
235 | * @deprecated |
||
236 | * @return int |
||
237 | */ |
||
238 | public function num_rows($pdo_statement='') |
||
239 | { |
||
240 | if ($pdo_statement) { |
||
241 | $pdo = clone $pdo_statement; |
||
242 | return count($pdo->fetchAll(PDO::FETCH_NUM)); |
||
243 | } else { |
||
244 | return 0; |
||
245 | } |
||
246 | } |
||
247 | |||
248 | /** |
||
249 | * Devuelve el nombre de un campo en el resultado de un select |
||
250 | * |
||
251 | * @param int $number |
||
252 | * @param resource $pdo_statement |
||
253 | * @return string |
||
254 | */ |
||
255 | public function field_name($number, $pdo_statement=NULL) |
||
256 | { |
||
257 | if (!$this->pdo) { |
||
258 | throw new KumbiaException('No hay conexión para realizar esta acción'); |
||
259 | } |
||
260 | if (!$pdo_statement) { |
||
261 | $pdo_statement = $this->pdo_statement; |
||
262 | if (!$pdo_statement) { |
||
263 | return false; |
||
264 | } |
||
265 | } |
||
266 | try { |
||
267 | $meta = $pdo_statement->getColumnMeta($number); |
||
268 | return $meta['name']; |
||
269 | } catch (PDOException $e) { |
||
270 | throw new KumbiaException($this->error($e->getMessage())); |
||
271 | } |
||
272 | } |
||
273 | |||
274 | /** |
||
275 | * Se Mueve al resultado indicado por $number en un select (No soportado por PDO) |
||
276 | * |
||
277 | * @param int $number |
||
278 | * @param PDOStatement $pdo_statement |
||
279 | * @return boolean |
||
280 | */ |
||
281 | public function data_seek($number, $pdo_statement=NULL) |
||
282 | { |
||
283 | return false; |
||
284 | } |
||
285 | |||
286 | /** |
||
287 | * Numero de Filas afectadas en un insert, update o delete |
||
288 | * |
||
289 | * @param resource $pdo_statement |
||
290 | * @deprecated |
||
291 | * @return int |
||
292 | */ |
||
293 | public function affected_rows($pdo_statement=NULL) |
||
294 | { |
||
295 | if (!$this->pdo) { |
||
296 | throw new KumbiaException('No hay conexión para realizar esta acción'); |
||
297 | } |
||
298 | if ($pdo_statement) { |
||
299 | try { |
||
300 | $row_count = $pdo_statement->rowCount(); |
||
301 | if ($row_count === false) { |
||
302 | throw new KumbiaException($this->error(" al ejecutar <em>\"$sql_query\"</em>")); |
||
303 | } |
||
304 | return $row_count; |
||
305 | } catch (PDOException $e) { |
||
306 | throw new KumbiaException($this->error($e->getMessage())); |
||
307 | } |
||
308 | } else { |
||
309 | return $this->affected_rows; |
||
310 | } |
||
311 | } |
||
312 | |||
313 | /** |
||
314 | * Devuelve el error de MySQL |
||
315 | * |
||
316 | * @return string |
||
317 | */ |
||
318 | public function error($err='') |
||
319 | { |
||
320 | if ($this->pdo) { |
||
321 | $error = $this->pdo->errorInfo(); |
||
322 | $error = $error[2]; |
||
323 | } else { |
||
324 | $error = ""; |
||
325 | } |
||
326 | $this->last_error.= $error . " [" . $err . "]"; |
||
327 | if ($this->logger) { |
||
328 | Logger::error($this->last_error); |
||
329 | } |
||
330 | return $this->last_error; |
||
331 | } |
||
332 | |||
333 | /** |
||
334 | * Devuelve el no error de MySQL |
||
335 | * |
||
336 | * @return int |
||
337 | */ |
||
338 | public function no_error($number=0) |
||
339 | { |
||
340 | if ($this->pdo) { |
||
341 | $error = $this->pdo->errorInfo(); |
||
342 | $number = $error[1]; |
||
343 | } |
||
344 | return $number; |
||
345 | } |
||
346 | |||
347 | /** |
||
348 | * Devuelve el ultimo id autonumerico generado en la BD |
||
349 | * |
||
350 | * @return string |
||
351 | */ |
||
352 | public function last_insert_id($table='', $primary_key='') |
||
353 | { |
||
354 | return $this->pdo->lastInsertId(); |
||
355 | } |
||
356 | |||
357 | /** |
||
358 | * Inicia una transacción si es posible |
||
359 | * |
||
360 | */ |
||
361 | public function begin() |
||
362 | { |
||
363 | return $this->pdo->beginTransaction(); |
||
364 | } |
||
365 | |||
366 | /** |
||
367 | * Cancela una transacción si es posible |
||
368 | * |
||
369 | */ |
||
370 | public function rollback() |
||
371 | { |
||
372 | return $this->pdo->rollBack(); |
||
373 | } |
||
374 | |||
375 | /** |
||
376 | * Hace commit sobre una transacción si es posible |
||
377 | * |
||
378 | */ |
||
379 | public function commit() |
||
380 | { |
||
381 | return $this->pdo->commit(); |
||
382 | } |
||
383 | |||
384 | /** |
||
385 | * Agrega comillas o simples segun soporte el RBDM |
||
386 | * |
||
387 | * @return string |
||
388 | */ |
||
389 | static public function add_quotes($value) |
||
390 | { |
||
391 | return "'" . addslashes($value) . "'"; |
||
392 | } |
||
393 | |||
394 | /** |
||
395 | * Realiza una inserción |
||
396 | * |
||
397 | * @param string $table |
||
398 | * @param array $values |
||
399 | * @param array $fields |
||
400 | * @return integer |
||
401 | */ |
||
402 | public function insert($table, $values, $fields=null) |
||
403 | { |
||
404 | //$insert_sql = ""; |
||
405 | if (is_array($values)) { |
||
406 | if (!count($values)) { |
||
407 | throw new KumbiaException("Imposible realizar inserción en $table sin datos"); |
||
408 | } |
||
409 | if (is_array($fields)) { |
||
410 | $insert_sql = "INSERT INTO $table (" . join(",", $fields) . ") VALUES (" . join(",", $values) . ")"; |
||
411 | } else { |
||
412 | $insert_sql = "INSERT INTO $table VALUES (" . join(",", $values) . ")"; |
||
413 | } |
||
414 | return $this->exec($insert_sql); |
||
415 | } else { |
||
416 | throw new KumbiaException('El segundo parametro para insert no es un Array'); |
||
417 | } |
||
418 | } |
||
419 | |||
420 | /** |
||
421 | * Actualiza registros en una tabla |
||
422 | * |
||
423 | * @param string $table |
||
424 | * @param array $fields |
||
425 | * @param array $values |
||
426 | * @param string $where_condition |
||
427 | * @return integer |
||
428 | */ |
||
429 | public function update($table, $fields, $values, $where_condition=null) |
||
430 | { |
||
431 | $update_sql = "UPDATE $table SET "; |
||
432 | if (count($fields) != count($values)) { |
||
433 | throw new KumbiaException('El número de valores a actualizar no es el mismo de los campos'); |
||
434 | } |
||
435 | $i = 0; |
||
436 | $update_values = array(); |
||
437 | foreach ($fields as $field) { |
||
438 | $update_values[] = $field . ' = ' . $values[$i]; |
||
439 | $i++; |
||
440 | } |
||
441 | $update_sql.= join(',', $update_values); |
||
442 | if ($where_condition != null) { |
||
443 | $update_sql.= " WHERE $where_condition"; |
||
444 | } |
||
445 | return $this->exec($update_sql); |
||
446 | } |
||
447 | |||
448 | /** |
||
449 | * Borra registros de una tabla! |
||
450 | * |
||
451 | * @param string $table |
||
452 | * @param string $where_condition |
||
453 | */ |
||
454 | public function delete($table, $where_condition) |
||
455 | { |
||
456 | if ($where_condition) { |
||
457 | return $this->exec("DELETE FROM $table WHERE $where_condition"); |
||
458 | } else { |
||
459 | return $this->exec("DELETE FROM $table"); |
||
460 | } |
||
461 | } |
||
462 | |||
463 | /** |
||
464 | * Devuelve la ultima sentencia sql ejecutada por el Adaptador |
||
465 | * |
||
466 | * @return string |
||
467 | */ |
||
468 | public function last_sql_query() |
||
469 | { |
||
470 | return $this->last_query; |
||
471 | } |
||
472 | |||
473 | } |
||
474 |