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 Database 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 Database, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
15 | class Database { |
||
16 | |||
17 | /** @var string $tablePrefix Prefix for database tables */ |
||
18 | private $tablePrefix; |
||
19 | |||
20 | /** @var resource[] $dbLinks Database connection resources */ |
||
21 | private $dbLinks = array(); |
||
22 | |||
23 | /** @var int $queryCount The number of queries made */ |
||
24 | private $queryCount = 0; |
||
25 | |||
26 | /** |
||
27 | * Query cache for select queries. |
||
28 | * |
||
29 | * Queries and their results are stored in this cache as: |
||
30 | * <code> |
||
31 | * $DB_QUERY_CACHE[query hash] => array(result1, result2, ... resultN) |
||
32 | * </code> |
||
33 | * @see \Elgg\Database::getResults() for details on the hash. |
||
34 | * |
||
35 | * @var \Elgg\Cache\LRUCache $queryCache The cache |
||
36 | */ |
||
37 | private $queryCache = null; |
||
38 | |||
39 | /** |
||
40 | * @var int $queryCacheSize The number of queries to cache |
||
41 | */ |
||
42 | private $queryCacheSize = 50; |
||
43 | |||
44 | /** |
||
45 | * Queries are saved to an array and executed using |
||
46 | * a function registered by register_shutdown_function(). |
||
47 | * |
||
48 | * Queries are saved as an array in the format: |
||
49 | * <code> |
||
50 | * $this->delayedQueries[] = array( |
||
51 | * 'q' => string $query, |
||
52 | * 'l' => string $query_type, |
||
53 | * 'h' => string $handler // a callback function |
||
54 | * ); |
||
55 | * </code> |
||
56 | * |
||
57 | * @var array $delayedQueries Queries to be run during shutdown |
||
58 | */ |
||
59 | private $delayedQueries = array(); |
||
60 | |||
61 | /** @var bool $installed Is the database installed? */ |
||
62 | private $installed = false; |
||
63 | |||
64 | /** @var \Elgg\Database\Config $config Database configuration */ |
||
65 | private $config; |
||
66 | |||
67 | /** @var \Elgg\Logger $logger The logger */ |
||
68 | private $logger; |
||
69 | |||
70 | /** |
||
71 | * Constructor |
||
72 | * |
||
73 | * @param \Elgg\Database\Config $config Database configuration |
||
74 | * @param \Elgg\Logger $logger The logger |
||
75 | */ |
||
76 | 7 | public function __construct(\Elgg\Database\Config $config, \Elgg\Logger $logger) { |
|
85 | |||
86 | /** |
||
87 | * Gets (if required, also creates) a database link resource. |
||
88 | * |
||
89 | * The database link resources are created by |
||
90 | * {@link \Elgg\Database::setupConnections()}, which is called if no links exist. |
||
91 | * |
||
92 | * @param string $type The type of link we want: "read", "write" or "readwrite". |
||
93 | * |
||
94 | * @return resource Database link |
||
95 | * @throws \DatabaseException |
||
96 | * @todo make protected once we get rid of get_db_link() |
||
97 | */ |
||
98 | public function getLink($type) { |
||
108 | |||
109 | /** |
||
110 | * Establish database connections |
||
111 | * |
||
112 | * If the configuration has been set up for multiple read/write databases, set those |
||
113 | * links up separately; otherwise just create the one database link. |
||
114 | * |
||
115 | * @return void |
||
116 | * @throws \DatabaseException |
||
117 | */ |
||
118 | public function setupConnections() { |
||
126 | |||
127 | |||
128 | /** |
||
129 | * Establish a connection to the database server |
||
130 | * |
||
131 | * Connect to the database server and use the Elgg database for a particular database link |
||
132 | * |
||
133 | * @param string $dblinkname The type of database connection. Used to identify the |
||
134 | * resource: "read", "write", or "readwrite". |
||
135 | * |
||
136 | * @return void |
||
137 | * @throws \DatabaseException |
||
138 | */ |
||
139 | public function establishLink($dblinkname = "readwrite") { |
||
158 | |||
159 | /** |
||
160 | * Retrieve rows from the database. |
||
161 | * |
||
162 | * Queries are executed with {@link \Elgg\Database::executeQuery()} and results |
||
163 | * are retrieved with {@link mysql_fetch_object()}. If a callback |
||
164 | * function $callback is defined, each row will be passed as a single |
||
165 | * argument to $callback. If no callback function is defined, the |
||
166 | * entire result set is returned as an array. |
||
167 | * |
||
168 | * @param mixed $query The query being passed. |
||
169 | * @param string $callback Optionally, the name of a function to call back to on each row |
||
170 | * |
||
171 | * @return array An array of database result objects or callback function results. If the query |
||
172 | * returned nothing, an empty array. |
||
173 | * @throws \DatabaseException |
||
174 | */ |
||
175 | public function getData($query, $callback = '') { |
||
178 | |||
179 | /** |
||
180 | * Retrieve a single row from the database. |
||
181 | * |
||
182 | * Similar to {@link \Elgg\Database::getData()} but returns only the first row |
||
183 | * matched. If a callback function $callback is specified, the row will be passed |
||
184 | * as the only argument to $callback. |
||
185 | * |
||
186 | * @param mixed $query The query to execute. |
||
187 | * @param string $callback A callback function |
||
188 | * |
||
189 | * @return mixed A single database result object or the result of the callback function. |
||
190 | * @throws \DatabaseException |
||
191 | */ |
||
192 | public function getDataRow($query, $callback = '') { |
||
195 | |||
196 | /** |
||
197 | * Insert a row into the database. |
||
198 | * |
||
199 | * @note Altering the DB invalidates all queries in the query cache. |
||
200 | * |
||
201 | * @param mixed $query The query to execute. |
||
202 | * |
||
203 | * @return int|false The database id of the inserted row if a AUTO_INCREMENT field is |
||
204 | * defined, 0 if not, and false on failure. |
||
205 | * @throws \DatabaseException |
||
206 | */ |
||
207 | View Code Duplication | public function insertData($query) { |
|
221 | |||
222 | /** |
||
223 | * Update the database. |
||
224 | * |
||
225 | * @note Altering the DB invalidates all queries in the query cache. |
||
226 | * |
||
227 | * @param string $query The query to run. |
||
228 | * @param bool $getNumRows Return the number of rows affected (default: false) |
||
229 | * |
||
230 | * @return bool|int |
||
231 | * @throws \DatabaseException |
||
232 | */ |
||
233 | public function updateData($query, $getNumRows = false) { |
||
251 | |||
252 | /** |
||
253 | * Delete data from the database |
||
254 | * |
||
255 | * @note Altering the DB invalidates all queries in query cache. |
||
256 | * |
||
257 | * @param string $query The SQL query to run |
||
258 | * |
||
259 | * @return int|false The number of affected rows or false on failure |
||
260 | * @throws \DatabaseException |
||
261 | */ |
||
262 | View Code Duplication | public function deleteData($query) { |
|
276 | |||
277 | /** |
||
278 | * Get a string that uniquely identifies a callback during the current request. |
||
279 | * |
||
280 | * This is used to cache queries whose results were transformed by the callback. If the callback involves |
||
281 | * object method calls of the same class, different instances will return different values. |
||
282 | * |
||
283 | * @param callable $callback The callable value to fingerprint |
||
284 | * |
||
285 | * @return string A string that is unique for each callable passed in |
||
286 | * @since 1.9.4 |
||
287 | * @access private |
||
288 | * @todo Make this protected once we can setAccessible(true) via reflection |
||
289 | */ |
||
290 | 1 | public function fingerprintCallback($callback) { |
|
306 | |||
307 | /** |
||
308 | * Handles queries that return results, running the results through a |
||
309 | * an optional callback function. This is for R queries (from CRUD). |
||
310 | * |
||
311 | * @param string $query The select query to execute |
||
312 | * @param string $callback An optional callback function to run on each row |
||
313 | * @param bool $single Return only a single result? |
||
314 | * |
||
315 | * @return array An array of database result objects or callback function results. If the query |
||
316 | * returned nothing, an empty array. |
||
317 | * @throws \DatabaseException |
||
318 | */ |
||
319 | protected function getResults($query, $callback = null, $single = false) { |
||
377 | |||
378 | /** |
||
379 | * Execute a query. |
||
380 | * |
||
381 | * $query is executed via {@link mysql_query()}. If there is an SQL error, |
||
382 | * a {@link DatabaseException} is thrown. |
||
383 | * |
||
384 | * @param string $query The query |
||
385 | * @param resource $dblink The DB link |
||
386 | * |
||
387 | * @return resource|bool The result of mysql_query() |
||
388 | * @throws \DatabaseException |
||
389 | * @todo should this be public? |
||
390 | */ |
||
391 | public function executeQuery($query, $dblink) { |
||
411 | |||
412 | /** |
||
413 | * Runs a full database script from disk. |
||
414 | * |
||
415 | * The file specified should be a standard SQL file as created by |
||
416 | * mysqldump or similar. Statements must be terminated with ; |
||
417 | * and a newline character (\n or \r\n). |
||
418 | * |
||
419 | * The special string 'prefix_' is replaced with the database prefix |
||
420 | * as defined in {@link $this->tablePrefix}. |
||
421 | * |
||
422 | * @warning Only single line comments are supported. A comment |
||
423 | * must start with '-- ' or '# ', where the comment sign is at the |
||
424 | * very beginning of each line. |
||
425 | * |
||
426 | * @warning Errors do not halt execution of the script. If a line |
||
427 | * generates an error, the error message is saved and the |
||
428 | * next line is executed. After the file is run, any errors |
||
429 | * are displayed as a {@link DatabaseException} |
||
430 | * |
||
431 | * @param string $scriptlocation The full path to the script |
||
432 | * |
||
433 | * @return void |
||
434 | * @throws \DatabaseException |
||
435 | */ |
||
436 | 5 | public function runSqlScript($scriptlocation) { |
|
473 | |||
474 | /** |
||
475 | * Queue a query for execution upon shutdown. |
||
476 | * |
||
477 | * You can specify a handler function if you care about the result. This function will accept |
||
478 | * the raw result from {@link mysql_query()}. |
||
479 | * |
||
480 | * @param string $query The query to execute |
||
481 | * @param string $type The query type ('read' or 'write') |
||
482 | * @param string $handler A callback function to pass the results array to |
||
483 | * |
||
484 | * @return boolean Whether registering was successful. |
||
485 | * @todo deprecate passing resource for $type as that should not be part of public API |
||
486 | */ |
||
487 | public function registerDelayedQuery($query, $type, $handler = "") { |
||
503 | |||
504 | |||
505 | /** |
||
506 | * Trigger all queries that were registered as "delayed" queries. This is |
||
507 | * called by the system automatically on shutdown. |
||
508 | * |
||
509 | * @return void |
||
510 | * @access private |
||
511 | * @todo make protected once this class is part of public API |
||
512 | */ |
||
513 | public function executeDelayedQueries() { |
||
537 | |||
538 | /** |
||
539 | * Enable the query cache |
||
540 | * |
||
541 | * This does not take precedence over the \Elgg\Database\Config setting. |
||
542 | * |
||
543 | * @return void |
||
544 | */ |
||
545 | 7 | public function enableQueryCache() { |
|
551 | |||
552 | /** |
||
553 | * Disable the query cache |
||
554 | * |
||
555 | * This is useful for special scripts that pull large amounts of data back |
||
556 | * in single queries. |
||
557 | * |
||
558 | * @return void |
||
559 | */ |
||
560 | public function disableQueryCache() { |
||
563 | |||
564 | /** |
||
565 | * Invalidate the query cache |
||
566 | * |
||
567 | * @return void |
||
568 | */ |
||
569 | protected function invalidateQueryCache() { |
||
575 | |||
576 | /** |
||
577 | * Test that the Elgg database is installed |
||
578 | * |
||
579 | * @return void |
||
580 | * @throws \InstallationException |
||
581 | */ |
||
582 | public function assertInstalled() { |
||
600 | |||
601 | /** |
||
602 | * Get the number of queries made to the database |
||
603 | * |
||
604 | * @return int |
||
605 | */ |
||
606 | public function getQueryCount() { |
||
609 | |||
610 | /** |
||
611 | * Get the prefix for Elgg's tables |
||
612 | * |
||
613 | * @return string |
||
614 | */ |
||
615 | 1 | public function getTablePrefix() { |
|
618 | |||
619 | /** |
||
620 | * Sanitizes an integer value for use in a query |
||
621 | * |
||
622 | * @param int $value Value to sanitize |
||
623 | * @param bool $signed Whether negative values are allowed (default: true) |
||
624 | * @return int |
||
625 | */ |
||
626 | 3 | public function sanitizeInt($value, $signed = true) { |
|
637 | |||
638 | /** |
||
639 | * Sanitizes a string for use in a query |
||
640 | * |
||
641 | * @param string $value Value to escape |
||
642 | * @return string |
||
643 | */ |
||
644 | public function sanitizeString($value) { |
||
653 | |||
654 | /** |
||
655 | * Get the server version number |
||
656 | * |
||
657 | * @param string $type Connection type (Config constants, e.g. Config::READ_WRITE) |
||
658 | * |
||
659 | * @return string |
||
660 | */ |
||
661 | public function getServerVersion($type) { |
||
664 | } |
||
665 | |||
666 |
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: