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 dbMySQL 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 dbMySQL, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 13 | class dbMySQL extends dbMySQLConnector |
||
|
|
|||
| 14 | { |
||
| 15 | /** |
||
| 16 | * Количество запросов класса |
||
| 17 | * @var integer |
||
| 18 | */ |
||
| 19 | private $query_count = 0; |
||
| 20 | |||
| 21 | /** Show hide query debug information */ |
||
| 22 | public function debug($flag = true) |
||
| 23 | { |
||
| 24 | if ($flag) { |
||
| 25 | $_SESSION['__AR_SHOW_QUERY__'] = true; |
||
| 26 | } else { |
||
| 27 | unset($_SESSION['__AR_SHOW_QUERY__']); |
||
| 28 | } |
||
| 29 | } |
||
| 30 | |||
| 31 | /** |
||
| 32 | * Check object $field field value as $table column |
||
| 33 | * and if database table does not have it - create. |
||
| 34 | * $field is not set in object - error returns |
||
| 35 | * |
||
| 36 | * @param object $object Pointer to object to get field names data |
||
| 37 | * @param string $table Database table name |
||
| 38 | * @param string $field Object field name |
||
| 39 | * @param string $type Database column name |
||
| 40 | * |
||
| 41 | * @return bool True if database table has field or field has been created |
||
| 42 | */ |
||
| 43 | public function createField($object, $table, $field, $type = 'INT') |
||
| 44 | { |
||
| 45 | // Check if db identifier field is configured |
||
| 46 | if (class_exists($table)) { |
||
| 47 | if (strlen($object->$field)) { |
||
| 48 | // Variable to get all social table attributes |
||
| 49 | $attributes = array(); |
||
| 50 | // Get table attributes - PHP 5.2 compatible |
||
| 51 | eval('$attributes = ' . $table . '::$_attributes;'); |
||
| 52 | |||
| 53 | // Remove namespaces |
||
| 54 | $table = \samson\core\AutoLoader::getOnlyClass($table); |
||
| 55 | |||
| 56 | // Make keys lowercase |
||
| 57 | $attributes = array_change_key_case_unicode($attributes); |
||
| 58 | |||
| 59 | // If table does not have defined identifier field |
||
| 60 | if (!isset($attributes[strtolower($object->$field)])) { |
||
| 61 | // Add identifier field to social users table |
||
| 62 | $this->simple_query('ALTER TABLE `' . $table . '` ADD `' . $object->$field . '` ' . $type . ' '); |
||
| 63 | } |
||
| 64 | |||
| 65 | return true; |
||
| 66 | |||
| 67 | } else { // Signal error |
||
| 68 | return e('Cannot load "' . get_class($object) . '" module - no $' . $field . ' is configured'); |
||
| 69 | } |
||
| 70 | } |
||
| 71 | } |
||
| 72 | |||
| 73 | // TODO: Очень узкое место для совместимости с 5.2 !!! |
||
| 74 | /** |
||
| 75 | * Обратная совместить с PHP < 5.3 т.к. там нельзя подставлять переменное имя класса |
||
| 76 | * в статическом контексте |
||
| 77 | * @param unknown_type $class_name |
||
| 78 | */ |
||
| 79 | public function __get_table_data($class_name) |
||
| 80 | { |
||
| 81 | // Remove table prefix |
||
| 82 | $class_name = str_replace(self::$prefix, '', $class_name); |
||
| 83 | |||
| 84 | // Сформируем правильное имя класса |
||
| 85 | $class_name = strpos($class_name, '\\') !== false ? $class_name : '\samson\activerecord\\'.$class_name; |
||
| 86 | |||
| 87 | // Сформируем комманды на получение статических переменных определенного класса |
||
| 88 | $_table_name = '$_table_name = ' . $class_name . '::$_table_name;'; |
||
| 89 | $_own_group = '$_own_group = ' . $class_name . '::$_own_group;'; |
||
| 90 | $_table_attributes = '$_table_attributes = ' . $class_name . '::$_table_attributes;'; |
||
| 91 | $_primary = '$_primary = ' . $class_name . '::$_primary;'; |
||
| 92 | $_sql_from = '$_sql_from = ' . $class_name . '::$_sql_from;'; |
||
| 93 | $_sql_select = '$_sql_select = ' . $class_name . '::$_sql_select;'; |
||
| 94 | $_attributes = '$_attributes = ' . $class_name . '::$_attributes;'; |
||
| 95 | $_types = '$_types = ' . $class_name . '::$_types;'; |
||
| 96 | $_map = '$_map = ' . $class_name . '::$_map;'; |
||
| 97 | $_relations = '$_relations = ' . $class_name . '::$_relations;'; |
||
| 98 | $_unique = '$_unique = ' . $class_name . '::$_unique;'; |
||
| 99 | $_relation_type = '$_relation_type = ' . $class_name . '::$_relation_type;'; |
||
| 100 | $_relation_alias = '$_relation_alias = ' . $class_name . '::$_relation_alias;'; |
||
| 101 | |||
| 102 | //trace($_table_name.$_primary.$_sql_from.$_sql_select.$_map.$_attributes.$_relations.$_relation_type.$_types.$_unique); |
||
| 103 | |||
| 104 | // Выполним специальный код получения значений переменной |
||
| 105 | eval($_own_group . $_table_name . $_primary . $_sql_from . $_sql_select . $_map . $_attributes . $_relations . $_relation_type . $_relation_alias . $_types . $_unique . $_table_attributes); |
||
| 106 | |||
| 107 | // Вернем массив имен переменных и их значений |
||
| 108 | return array |
||
| 109 | ( |
||
| 110 | '_table_name' => $_table_name, |
||
| 111 | '_own_group' => $_own_group, |
||
| 112 | '_primary' => $_primary, |
||
| 113 | '_attributes' => $_attributes, |
||
| 114 | '_table_attributes' => $_table_attributes, |
||
| 115 | '_types' => $_types, |
||
| 116 | '_map' => $_map, |
||
| 117 | '_relations' => $_relations, |
||
| 118 | '_relation_type' => $_relation_type, |
||
| 119 | '_relation_alias' => $_relation_alias, |
||
| 120 | '_sql_from' => $_sql_from, |
||
| 121 | '_sql_select' => $_sql_select, |
||
| 122 | '_unique' => $_unique, |
||
| 123 | ); |
||
| 124 | } |
||
| 125 | |||
| 126 | public function create($className, &$object = null) |
||
| 127 | { |
||
| 128 | // ?? |
||
| 129 | $fields = $this->getQueryFields($className, $object); |
||
| 130 | // Build SQL query |
||
| 131 | $sql = 'INSERT INTO `' . $className::$_table_name . '` (`' |
||
| 132 | . implode('`,`', array_keys($fields)) . '`) |
||
| 133 | VALUES (' . implode(',', $fields) . ')'; |
||
| 134 | $this->query($sql); |
||
| 135 | // Return last inserted row identifier |
||
| 136 | return $this->driver->lastInsertId(); |
||
| 137 | } |
||
| 138 | |||
| 139 | public function update($className, &$object) |
||
| 140 | { |
||
| 141 | // ?? |
||
| 142 | $fields = $this->getQueryFields($className, $object, true); |
||
| 143 | // Build SQL query |
||
| 144 | $sql = 'UPDATE `' . $className::$_table_name . '` SET ' . implode(',', |
||
| 145 | $fields) . ' WHERE ' . $className::$_table_name . '.' . $className::$_primary . '="' . $object->id . '"'; |
||
| 146 | $this->query($sql); |
||
| 147 | } |
||
| 148 | |||
| 149 | public function delete($className, &$object) |
||
| 150 | { |
||
| 151 | // Build SQL query |
||
| 152 | $sql = 'DELETE FROM `' . $className::$_table_name . '` WHERE ' . $className::$_primary . ' = "' . $object->id . '"'; |
||
| 153 | $this->query($sql); |
||
| 154 | } |
||
| 155 | |||
| 156 | /** |
||
| 157 | * @see idb::find() |
||
| 158 | */ |
||
| 159 | public function &find($class_name, QueryInterface $query) |
||
| 160 | { |
||
| 161 | // Результат выполнения запроса |
||
| 162 | $result = array(); |
||
| 163 | |||
| 164 | if ($query->empty) { |
||
| 165 | return $result; |
||
| 166 | } |
||
| 167 | |||
| 168 | // Get SQL |
||
| 169 | $sql = $this->prepareSQL($class_name, $query); |
||
| 170 | |||
| 171 | // Выполним запрос к БД |
||
| 172 | $db_data = $this->fetch($sql); |
||
| 173 | |||
| 174 | //trace($query->virtual_fields); |
||
| 175 | |||
| 176 | // Выполним запрос к БД и создадим объекты |
||
| 177 | if ((is_array($db_data)) && (sizeof($db_data) > 0)) { |
||
| 178 | $result = $this->toRecords($class_name, $db_data, $query->join, |
||
| 179 | array_merge($query->own_virtual_fields, $query->virtual_fields)); |
||
| 180 | } |
||
| 181 | |||
| 182 | // Вернем коллекцию полученных объектов |
||
| 183 | return $result; |
||
| 184 | } |
||
| 185 | |||
| 186 | |||
| 187 | /** |
||
| 188 | * @see idb::find_by_id() |
||
| 189 | */ |
||
| 190 | public function &find_by_id($class_name, $id) |
||
| 212 | |||
| 213 | /** |
||
| 214 | * Выполнить защиту значения поля для его безопасного использования в запросах |
||
| 215 | * |
||
| 216 | * @param string $value Значения поля для запроса |
||
| 217 | * @return string $value Безопасное представление значения поля для запроса |
||
| 218 | */ |
||
| 219 | protected function protectQueryValue($value) |
||
| 220 | { |
||
| 221 | // If magic quotes are on - remove slashes |
||
| 222 | if (get_magic_quotes_gpc()) { |
||
| 223 | $value = stripslashes($value); |
||
| 224 | } |
||
| 225 | |||
| 226 | // Normally escape string |
||
| 227 | $value = $this->driver->quote($value); |
||
| 228 | |||
| 229 | // Return value in quotes |
||
| 230 | return $value; |
||
| 231 | } |
||
| 232 | |||
| 233 | /** @deprecated Use execute() */ |
||
| 234 | public function simple_query($sql) |
||
| 238 | |||
| 239 | /** |
||
| 240 | * Prepare create & update SQL statements fields |
||
| 241 | * @param string $className Entity name |
||
| 242 | * @param Record $object Database object to get values(if needed) |
||
| 243 | * @param bool $straight Way of forming SQL field statements |
||
| 244 | * @return array Collection of key => value with SQL fields statements |
||
| 245 | */ |
||
| 246 | protected function &getQueryFields($className, & $object = null, $straight = false) |
||
| 278 | |||
| 279 | /** |
||
| 280 | * Generic database migration handler |
||
| 281 | * @param string $classname Class for searching migration methods |
||
| 282 | * @param string $version_handler External handler for interacting with database version |
||
| 283 | */ |
||
| 284 | public function migration($classname, $version_handler) |
||
| 322 | |||
| 323 | /** @see idb::profiler() */ |
||
| 324 | public function profiler() |
||
| 348 | |||
| 349 | /** Count query result */ |
||
| 350 | public function innerCount($className, $query) |
||
| 363 | |||
| 364 | // |
||
| 365 | // Приватный контекст |
||
| 366 | // |
||
| 367 | |||
| 368 | /** |
||
| 369 | * Create SQL request |
||
| 370 | * |
||
| 371 | * @param string $class_name Classname for request creating |
||
| 372 | * @param QueryInterface $query Query with parameters |
||
| 373 | * @return string SQL string |
||
| 374 | */ |
||
| 375 | protected function prepareSQL($class_name, QueryInterface $query) |
||
| 448 | |||
| 449 | protected function prepareInnerSQL($class_name, QueryInterface $query, $params) |
||
| 486 | |||
| 487 | protected function getConditions(ConditionInterface $cond_group, $class_name) |
||
| 511 | |||
| 512 | /** |
||
| 513 | * "Правильно" разпознать переданный аргумент условия запроса к БД |
||
| 514 | * |
||
| 515 | * @param string $class_name Схема сущности БД для которой данные условия |
||
| 516 | * @param Argument $arg Аругемнт условия для преобразования |
||
| 517 | * @return string Возвращает разпознанную строку с условием для MySQL |
||
| 518 | */ |
||
| 519 | protected function parseCondition($class_name, & $arg) |
||
| 561 | |||
| 562 | |||
| 563 | /** |
||
| 564 | * Create object instance by specified parameters |
||
| 565 | * @param string $className Object class name |
||
| 566 | * @param RelationData $metaData Object metadata for creation and filling |
||
| 567 | * @param array $dbData Database record with object data |
||
| 568 | * |
||
| 569 | * @return idbRecord Database record object instance |
||
| 570 | */ |
||
| 571 | public function &createObject( |
||
| 613 | |||
| 614 | /** |
||
| 615 | * Преобразовать массив записей из БД во внутреннее представление dbRecord |
||
| 616 | * @param string $class_name Имя класса |
||
| 617 | * @param array $response Массив записей полученных из БД |
||
| 618 | * @return array Коллекцию записей БД во внутреннем формате |
||
| 619 | * @see dbRecord |
||
| 620 | */ |
||
| 621 | protected function &toRecords($class_name, array & $response, array $join = array(), array $virtual_fields = array()) |
||
| 766 | } |
||
| 767 |
Classes in PHP are usually named in CamelCase.
In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.
Thus the name database provider becomes
DatabaseProvider.