123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180 |
- <?php
- namespace think;
- use think\db\Connection;
- use think\db\Query;
- class Db
- {
-
- private static $instance = [];
-
- public static $queryTimes = 0;
-
- public static $executeTimes = 0;
-
- public static function connect($config = [], $name = false)
- {
- if (false === $name) {
- $name = md5(serialize($config));
- }
- if (true === $name || !isset(self::$instance[$name])) {
-
- $options = self::parseConfig($config);
- if (empty($options['type'])) {
- throw new \InvalidArgumentException('Undefined db type');
- }
- $class = false !== strpos($options['type'], '\\') ?
- $options['type'] :
- '\\think\\db\\connector\\' . ucwords($options['type']);
-
- if (App::$debug) {
- Log::record('[ DB ] INIT ' . $options['type'], 'info');
- }
- if (true === $name) {
- $name = md5(serialize($config));
- }
- self::$instance[$name] = new $class($options);
- }
- return self::$instance[$name];
- }
-
- public static function clear()
- {
- self::$instance = [];
- }
-
- private static function parseConfig($config)
- {
- if (empty($config)) {
- $config = Config::get('database');
- } elseif (is_string($config) && false === strpos($config, '/')) {
- $config = Config::get($config);
- }
- return is_string($config) ? self::parseDsn($config) : $config;
- }
-
- private static function parseDsn($dsnStr)
- {
- $info = parse_url($dsnStr);
- if (!$info) {
- return [];
- }
- $dsn = [
- 'type' => $info['scheme'],
- 'username' => isset($info['user']) ? $info['user'] : '',
- 'password' => isset($info['pass']) ? $info['pass'] : '',
- 'hostname' => isset($info['host']) ? $info['host'] : '',
- 'hostport' => isset($info['port']) ? $info['port'] : '',
- 'database' => !empty($info['path']) ? ltrim($info['path'], '/') : '',
- 'charset' => isset($info['fragment']) ? $info['fragment'] : 'utf8',
- ];
- if (isset($info['query'])) {
- parse_str($info['query'], $dsn['params']);
- } else {
- $dsn['params'] = [];
- }
- return $dsn;
- }
-
- public static function __callStatic($method, $params)
- {
- return call_user_func_array([self::connect(), $method], $params);
- }
- }
|