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:
| 1 | <?php |
||
| 40 | class Database extends Medoo |
||
| 41 | { |
||
| 42 | /** |
||
| 43 | * SQL queries |
||
| 44 | * |
||
| 45 | * @var array |
||
| 46 | */ |
||
| 47 | public static $queries = []; |
||
| 48 | |||
| 49 | /** |
||
| 50 | * Instance Handle |
||
| 51 | * |
||
| 52 | * @var array |
||
| 53 | */ |
||
| 54 | protected static $instance; |
||
| 55 | |||
| 56 | /** |
||
| 57 | * Disable Clone |
||
| 58 | * |
||
| 59 | * @return boolean |
||
| 60 | */ |
||
| 61 | public function __clone() |
||
| 62 | { |
||
| 63 | return false; |
||
| 64 | } |
||
| 65 | |||
| 66 | /** |
||
| 67 | * Get singleton |
||
| 68 | * |
||
| 69 | * @param string $key |
||
| 70 | * @return object |
||
| 71 | * |
||
| 72 | * @throws \Kotori\Exception\DatabaseException |
||
| 73 | */ |
||
| 74 | 2 | public static function getInstance($key = null) |
|
| 75 | { |
||
| 76 | 2 | $config = Container::get('config')->get('db'); |
|
| 77 | 2 | if (!is_array($config) || count($config) == 0) { |
|
| 78 | 2 | return null; |
|
| 79 | } elseif ($key == null) { |
||
|
|
|||
| 80 | $dbKeys = array_keys($config); |
||
| 81 | if (isset($dbKeys[0])) { |
||
| 82 | $key = $dbKeys[0]; |
||
| 83 | } else { |
||
| 84 | return null; |
||
| 85 | } |
||
| 86 | } |
||
| 87 | |||
| 88 | Container::get('config')->set('selected_db_key', $key); |
||
| 89 | |||
| 90 | if (!isset(self::$instance[$key])) { |
||
| 91 | try { |
||
| 92 | self::$instance[$key] = new self($config[$key]); |
||
| 93 | } catch (PDOException $e) { |
||
| 94 | throw new DatabaseException($e); |
||
| 95 | } catch (Exception $e) { |
||
| 96 | throw new DatabaseException($e); |
||
| 97 | } |
||
| 98 | } |
||
| 99 | |||
| 100 | return self::$instance[$key]; |
||
| 101 | } |
||
| 102 | |||
| 103 | /** |
||
| 104 | * Class constructor |
||
| 105 | * |
||
| 106 | * Initialize Database. |
||
| 107 | */ |
||
| 108 | public function __construct(array $options = []) |
||
| 121 | |||
| 122 | /** |
||
| 123 | * medoo::query() |
||
| 124 | * |
||
| 125 | * @param string $query |
||
| 126 | * @param array $map |
||
| 127 | * @return \PDOStatement |
||
| 128 | */ |
||
| 129 | View Code Duplication | public function query($query, $map = []) |
|
| 137 | |||
| 138 | /** |
||
| 139 | * medoo:exec() |
||
| 140 | * |
||
| 141 | * @param string $query |
||
| 142 | * @param array $map |
||
| 143 | * @return \PDOStatement |
||
| 144 | */ |
||
| 145 | 4 | View Code Duplication | public function exec($query, $map = []) |
| 153 | } |
||
| 154 |