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 MySQL 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 MySQL, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
19 | class MySQL |
||
20 | { |
||
21 | /** |
||
22 | * Constant to indicate whether the query is a write operation. |
||
23 | * |
||
24 | * @var integer |
||
25 | */ |
||
26 | const __WRITE_OPERATION__ = 0; |
||
27 | |||
28 | /** |
||
29 | * Constant to indicate whether the query is a write operation |
||
30 | * |
||
31 | * @var integer |
||
32 | */ |
||
33 | const __READ_OPERATION__ = 1; |
||
34 | |||
35 | /** |
||
36 | * An associative array of connection properties for this MySQL |
||
37 | * database including the host, port, username, password and |
||
38 | * selected database. |
||
39 | * |
||
40 | * @var Database |
||
41 | */ |
||
42 | private static $_conn_pdo = null; |
||
43 | |||
44 | /** |
||
45 | * Sets the current `$_log` to be an empty array |
||
46 | */ |
||
47 | public static function flushLog() |
||
51 | |||
52 | /** |
||
53 | * Returns the number of queries that has been executed |
||
54 | * |
||
55 | * @return integer |
||
56 | */ |
||
57 | public static function queryCount() |
||
61 | |||
62 | /** |
||
63 | * Symphony uses a prefix for all it's database tables so it can live peacefully |
||
64 | * on the same database as other applications. By default this is `sym_`, but it |
||
65 | * can be changed when Symphony is installed. |
||
66 | * |
||
67 | * @param string $prefix |
||
68 | * The table prefix for Symphony, by default this is `sym_` |
||
69 | */ |
||
70 | public function setPrefix($prefix) |
||
75 | |||
76 | /** |
||
77 | * Returns the prefix used by Symphony for this Database instance. |
||
78 | * |
||
79 | * @since Symphony 2.4 |
||
80 | * @return string |
||
81 | */ |
||
82 | public function getPrefix() |
||
86 | |||
87 | /** |
||
88 | * Determines if a connection has been made to the MySQL server |
||
89 | * |
||
90 | * @return boolean |
||
91 | */ |
||
92 | public static function isConnected() |
||
104 | |||
105 | /** |
||
106 | * Sets query caching to true, this will prepend all READ_OPERATION |
||
107 | * queries with SQL_CACHE. Symphony be default enables caching. It |
||
108 | * can be turned off by setting the query_cache parameter to 'off' in the |
||
109 | * Symphony config file. |
||
110 | * |
||
111 | * @link http://dev.mysql.com/doc/refman/5.1/en/query-cache.html |
||
112 | */ |
||
113 | public function enableCaching() |
||
117 | |||
118 | /** |
||
119 | * Sets query caching to false, this will prepend all READ_OPERATION |
||
120 | * queries will SQL_NO_CACHE. |
||
121 | */ |
||
122 | public function disableCaching() |
||
126 | |||
127 | /** |
||
128 | * Returns boolean if query caching is enabled or not |
||
129 | * |
||
130 | * @return boolean |
||
131 | */ |
||
132 | public function isCachingEnabled() |
||
136 | |||
137 | /** |
||
138 | * Enables query logging and profiling. |
||
139 | * |
||
140 | * @since Symphony 2.6.2 |
||
141 | */ |
||
142 | public static function enableLogging() |
||
146 | |||
147 | /** |
||
148 | * Disables query logging and profiling. Use this in low memory environments |
||
149 | * to reduce memory usage. |
||
150 | * |
||
151 | * @since Symphony 2.6.2 |
||
152 | * @link https://github.com/symphonycms/symphony-2/issues/2398 |
||
153 | */ |
||
154 | public static function disableLogging() |
||
158 | |||
159 | /** |
||
160 | * Returns boolean if logging is enabled or not |
||
161 | * |
||
162 | * @since Symphony 2.6.2 |
||
163 | * @return boolean |
||
164 | */ |
||
165 | public static function isLoggingEnabled() |
||
169 | |||
170 | /** |
||
171 | * Creates a connect to the database server given the credentials. If an |
||
172 | * error occurs, a `DatabaseException` is thrown, otherwise true is returned |
||
173 | * |
||
174 | * @param string $host |
||
175 | * Defaults to null, which MySQL assumes as localhost. |
||
176 | * @param string $user |
||
177 | * Defaults to null |
||
178 | * @param string $password |
||
179 | * Defaults to null |
||
180 | * @param string $port |
||
181 | * Defaults to 3306. |
||
182 | * @param null $database |
||
183 | * @throws DatabaseException |
||
184 | * @return boolean |
||
185 | */ |
||
186 | public function connect($host = null, $user = null, $password = null, $port = '3306', $database = null) |
||
208 | |||
209 | /** |
||
210 | * Accessor for the current MySQL resource from PHP. May be |
||
211 | * useful for developers who want complete control over their |
||
212 | * database queries and don't want anything abstract by the MySQL |
||
213 | * class. |
||
214 | * |
||
215 | * @return PDO |
||
216 | */ |
||
217 | public static function getConnectionResource() |
||
221 | |||
222 | /** |
||
223 | * Sets the MySQL connection to use this timezone instead of the default |
||
224 | * MySQL server timezone. |
||
225 | * |
||
226 | * @throws DatabaseException |
||
227 | * @link https://dev.mysql.com/doc/refman/5.6/en/time-zone-support.html |
||
228 | * @link https://github.com/symphonycms/symphony-2/issues/1726 |
||
229 | * @since Symphony 2.3.3 |
||
230 | * @param string $timezone |
||
231 | * Timezone will human readable, such as Australia/Brisbane. |
||
232 | */ |
||
233 | public function setTimeZone($timezone = null) |
||
250 | |||
251 | /** |
||
252 | * This function will clean a string using the `mysqli_real_escape_string` function |
||
253 | * taking into account the current database character encoding. Note that this |
||
254 | * function does not encode _ or %. If `mysqli_real_escape_string` doesn't exist, |
||
255 | * `addslashes` will be used as a backup option |
||
256 | * |
||
257 | * @param string $value |
||
258 | * The string to be encoded into an escaped SQL string |
||
259 | * @return string |
||
260 | * The escaped SQL string |
||
261 | */ |
||
262 | public static function cleanValue($value) |
||
266 | |||
267 | /** |
||
268 | * This function will apply the `cleanValue` function to an associative |
||
269 | * array of data, encoding only the value, not the key. This function |
||
270 | * can handle recursive arrays. This function manipulates the given |
||
271 | * parameter by reference. |
||
272 | * |
||
273 | * @see cleanValue |
||
274 | * @param array $array |
||
275 | * The associative array of data to encode, this parameter is manipulated |
||
276 | * by reference. |
||
277 | */ |
||
278 | public static function cleanFields(array &$array) |
||
293 | |||
294 | /** |
||
295 | * Takes an SQL string and creates a prepared statement. |
||
296 | * |
||
297 | * @link http://php.net/manual/en/pdo.prepare.php |
||
298 | * @param string $query |
||
299 | * @param array $driver_options |
||
300 | * This array holds one or more key=>value pairs to set attribute values |
||
301 | * for the DatabaseStatement object that this method returns. |
||
302 | * @return DatabaseStatement |
||
303 | */ |
||
304 | public function prepare($query, array $driver_options = array()) |
||
308 | |||
309 | /** |
||
310 | * Create a transaction. |
||
311 | * |
||
312 | * @return DatabaseTransaction |
||
313 | */ |
||
314 | public function transaction() |
||
318 | |||
319 | /** |
||
320 | * Takes an SQL string and executes it. This function will apply query |
||
321 | * caching if it is a read operation and if query caching is set. Symphony |
||
322 | * will convert the `tbl_` prefix of tables to be the one set during installation. |
||
323 | * To automatically sanitize variables being used the query has to be sprintf-formatted |
||
324 | * and all variables passed on separately using the second parameter. |
||
325 | * A type parameter is provided to specify whether `$this->_lastResult` will be an array |
||
326 | * of objects or an array of associative arrays. The default is objects. This |
||
327 | * function will return boolean, but set `$this->_lastResult` to the result. |
||
328 | * |
||
329 | * @uses PostQueryExecution |
||
330 | * @param string $query |
||
331 | * The full SQL query to execute. |
||
332 | * @param string $type |
||
333 | * Whether to return the result as objects or associative array. Defaults |
||
334 | * to OBJECT which will return objects. The other option is ASSOC. If $type |
||
335 | * is not either of these, it will return objects. |
||
336 | * @throws DatabaseException |
||
337 | * @return boolean |
||
338 | * True if the query executed without errors, false otherwise |
||
339 | */ |
||
340 | public function query($query, $type = "OBJECT", $params = array()) |
||
350 | |||
351 | /** |
||
352 | * Returns the last insert ID from the previous query. This is |
||
353 | * the value from an auto_increment field. |
||
354 | * |
||
355 | * @return integer |
||
356 | * The last interested row's ID |
||
357 | */ |
||
358 | public function getInsertID() |
||
362 | |||
363 | /** |
||
364 | * A convenience method to insert data into the Database. This function |
||
365 | * takes an associative array of data to input, with the keys being the column |
||
366 | * names and the table. An optional parameter exposes MySQL's ON DUPLICATE |
||
367 | * KEY UPDATE functionality, which will update the values if a duplicate key |
||
368 | * is found. |
||
369 | * |
||
370 | * @param array $fields |
||
371 | * An associative array of data to input, with the key's mapping to the |
||
372 | * column names. Alternatively, an array of associative array's can be |
||
373 | * provided, which will perform multiple inserts |
||
374 | * @param string $table |
||
375 | * The table name, including the tbl prefix which will be changed |
||
376 | * to this Symphony's table prefix in the query function |
||
377 | * @param boolean $updateOnDuplicate |
||
378 | * If set to true, data will updated if any key constraints are found that cause |
||
379 | * conflicts. By default this is set to false, which will not update the data and |
||
380 | * would return an SQL error |
||
381 | * @throws DatabaseException |
||
382 | * @return boolean |
||
383 | */ |
||
384 | public function insert(array $fields, $table, $updateOnDuplicate=false) |
||
429 | |||
430 | /** |
||
431 | * A convenience method to update data that exists in the Database. This function |
||
432 | * takes an associative array of data to input, with the keys being the column |
||
433 | * names and the table. A WHERE statement can be provided to select the rows |
||
434 | * to update |
||
435 | * |
||
436 | * @param array $fields |
||
437 | * An associative array of data to input, with the key's mapping to the |
||
438 | * column names. |
||
439 | * @param string $table |
||
440 | * The table name, including the tbl prefix which will be changed |
||
441 | * to this Symphony's table prefix in the query function |
||
442 | * @param string $where |
||
443 | * A WHERE statement for this UPDATE statement, defaults to null |
||
444 | * which will update all rows in the $table |
||
445 | * @throws DatabaseException |
||
446 | * @return boolean |
||
447 | */ |
||
448 | public function update($fields, $table, $where = null, $params = array()) |
||
460 | |||
461 | /** |
||
462 | * Given a table name and a WHERE statement, delete rows from the |
||
463 | * Database. |
||
464 | * |
||
465 | * @param string $table |
||
466 | * The table name, including the tbl prefix which will be changed |
||
467 | * to this Symphony's table prefix in the query function |
||
468 | * @param string $where |
||
469 | * A WHERE statement for this DELETE statement, defaults to null, |
||
470 | * which will delete all rows in the $table |
||
471 | * @throws DatabaseException |
||
472 | * @return boolean |
||
473 | */ |
||
474 | View Code Duplication | public function delete($table, $where = null, array $params = array()) |
|
484 | |||
485 | /** |
||
486 | * Returns an associative array that contains the results of the |
||
487 | * given `$query`. Optionally, the resulting array can be indexed |
||
488 | * by a particular column. |
||
489 | * |
||
490 | * @param string $query |
||
491 | * The full SQL query to execute. Defaults to null, which will |
||
492 | * use the _lastResult |
||
493 | * @param array $params |
||
494 | * An array containing parameters to be used in the query. The query has to be |
||
495 | * sprintf-formatted. All values will be sanitized before being used in the query. |
||
496 | * For sake of backwards-compatibility, the query will only be sprintf-processed |
||
497 | * if $params is not empty. |
||
498 | * @param string $index_by_column |
||
499 | * The name of a column in the table to use it's value to index |
||
500 | * the result by. If this is omitted (and it is by default), an |
||
501 | * array of associative arrays is returned, with the key being the |
||
502 | * column names |
||
503 | * @throws DatabaseException |
||
504 | * @return array |
||
505 | * An associative array with the column names as the keys |
||
506 | */ |
||
507 | View Code Duplication | public function fetch($query = null, $index_by_column = null, array $params = array(), array $values = array()) |
|
515 | |||
516 | /** |
||
517 | * Returns the row at the specified index from the given query. If no |
||
518 | * query is given, it will use the `$this->_lastResult`. If no offset is provided, |
||
519 | * the function will return the first row. This function does not imply any |
||
520 | * LIMIT to the given `$query`, so for the more efficient use, it is recommended |
||
521 | * that the `$query` have a LIMIT set. |
||
522 | * |
||
523 | * @param integer $offset |
||
524 | * The row to return from the SQL query. For instance, if the second |
||
525 | * row from the result was required, the offset would be 1, because it |
||
526 | * is zero based. |
||
527 | * @param string $query |
||
528 | * The full SQL query to execute. Defaults to null, which will |
||
529 | * use the `$this->_lastResult` |
||
530 | * @throws DatabaseException |
||
531 | * @return array |
||
532 | * If there is no row at the specified `$offset`, an empty array will be returned |
||
533 | * otherwise an associative array of that row will be returned. |
||
534 | */ |
||
535 | public function fetchRow($offset = 0, $query = null, array $values = array()) |
||
543 | |||
544 | /** |
||
545 | * Returns an array of values for a specified column in a given query. |
||
546 | * If no query is given, it will use the `$this->_lastResult`. |
||
547 | * |
||
548 | * @param string $column |
||
549 | * The column name in the query to return the values for |
||
550 | * @param string $query |
||
551 | * The full SQL query to execute. Defaults to null, which will |
||
552 | * use the `$this->_lastResult` |
||
553 | * @throws DatabaseException |
||
554 | * @return array |
||
555 | * If there is no results for the `$query`, an empty array will be returned |
||
556 | * otherwise an array of values for that given `$column` will be returned |
||
557 | */ |
||
558 | public function fetchCol($column, $query = null, array $values = array()) |
||
573 | |||
574 | /** |
||
575 | * Returns the value for a specified column at a specified offset. If no |
||
576 | * offset is provided, it will return the value for column of the first row. |
||
577 | * If no query is given, it will use the `$this->_lastResult`. |
||
578 | * |
||
579 | * @param string $column |
||
580 | * The column name in the query to return the values for |
||
581 | * @param integer $offset |
||
582 | * The row to use to return the value for the given `$column` from the SQL |
||
583 | * query. For instance, if `$column` form the second row was required, the |
||
584 | * offset would be 1, because it is zero based. |
||
585 | * @param string $query |
||
586 | * The full SQL query to execute. Defaults to null, which will |
||
587 | * use the `$this->_lastResult` |
||
588 | * @param array $params |
||
589 | * An array containing parameters to be used in the query. The query has to be |
||
590 | * sprintf-formatted. All values will be sanitized before being used in the query. |
||
591 | * For sake of backwards-compatibility, the query will only be sprintf-processed |
||
592 | * if $params is not empty. |
||
593 | * @return string |
||
594 | * Returns the value of the given column, if it doesn't exist, null will be |
||
595 | * returned |
||
596 | */ |
||
597 | public function fetchVar($column, $offset = 0, $query = null, array $values = array()) |
||
603 | |||
604 | /** |
||
605 | * This function takes `$table` and `$field` names and returns boolean |
||
606 | * if the `$table` contains the `$field`. |
||
607 | * |
||
608 | * @since Symphony 2.3 |
||
609 | * @param string $table |
||
610 | * The table name |
||
611 | * @param string $field |
||
612 | * The field name |
||
613 | * @throws DatabaseException |
||
614 | * @return boolean |
||
615 | * True if `$table` contains `$field`, false otherwise |
||
616 | */ |
||
617 | public function tableContainsField($table, $field) |
||
623 | |||
624 | /** |
||
625 | * This function takes `$table` and returns boolean |
||
626 | * if it exists or not. |
||
627 | * |
||
628 | * @since Symphony 2.3.4 |
||
629 | * @param string $table |
||
630 | * The table name |
||
631 | * @throws DatabaseException |
||
632 | * @return boolean |
||
633 | * True if `$table` exists, false otherwise |
||
634 | */ |
||
635 | public function tableExists($table) |
||
644 | |||
645 | /** |
||
646 | * If an error occurs in a query, this function is called which logs |
||
647 | * the last query and the error number and error message from MySQL |
||
648 | * before throwing a `DatabaseException` |
||
649 | * |
||
650 | * @uses QueryExecutionError |
||
651 | * @throws DatabaseException |
||
652 | * @param string $type |
||
653 | * Accepts one parameter, 'connect', which will return the correct |
||
654 | * error codes when the connection sequence fails |
||
655 | */ |
||
656 | private function __error() |
||
660 | |||
661 | /** |
||
662 | * Returns all the log entries by type. There are two valid types, |
||
663 | * error and debug. If no type is given, the entire log is returned, |
||
664 | * otherwise only log messages for that type are returned |
||
665 | * |
||
666 | * @param null|string $type |
||
667 | * @return array |
||
668 | * An array of associative array's. Log entries of the error type |
||
669 | * return the query the error occurred on and the error number and |
||
670 | * message from MySQL. Log entries of the debug type return the |
||
671 | * the query and the start/stop time to indicate how long it took |
||
672 | * to run |
||
673 | */ |
||
674 | public function debug($type = null) |
||
678 | |||
679 | /** |
||
680 | * Returns some basic statistics from the MySQL class about the |
||
681 | * number of queries, the time it took to query and any slow queries. |
||
682 | * A slow query is defined as one that took longer than 0.0999 seconds |
||
683 | * This function is used by the Profile devkit |
||
684 | * |
||
685 | * @return array |
||
686 | * An associative array with the number of queries, an array of slow |
||
687 | * queries and the total query time. |
||
688 | */ |
||
689 | public function getStatistics() |
||
693 | |||
694 | /** |
||
695 | * Convenience function to allow you to execute multiple SQL queries at once |
||
696 | * by providing a string with the queries delimited with a `;` |
||
697 | * |
||
698 | * @throws DatabaseException |
||
699 | * @throws Exception |
||
700 | * @param string $sql |
||
701 | * A string containing SQL queries delimited by `;` |
||
702 | * @return boolean |
||
703 | * If one of the queries fails, false will be returned and no further queries |
||
704 | * will be executed, otherwise true will be returned. |
||
705 | */ |
||
706 | public function import($sql) |
||
716 | } |
||
717 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: