DBTrait.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Common;
  3. trait DBTrait
  4. {
  5. public static $db = null;
  6. public static $redis = null;
  7. public static $mongo = null;
  8. public static $db_config = [
  9. 'host' => '192.168.10.10',
  10. 'port' => 3306,
  11. 'user' => 'homestead',
  12. 'password' => 'secret',
  13. 'db_name' => 'weilaibike'
  14. ];
  15. public static $redis_config = [
  16. 'host' => '127.0.0.1',
  17. 'port' => 6379,
  18. 'password' => '',
  19. 'database' => 0
  20. ];
  21. public static $mongodb_config = [
  22. 'url' => 'mongodb://114.116.38.6',
  23. 'database' => 'weilaibike'
  24. ];
  25. public static function initDataBase($config = [1, 2, 3])
  26. {
  27. if (in_array(1, $config)) {
  28. self::$db_config = Config['db'];
  29. self::$db = new \Workerman\MySQL\Connection(self::$db_config['host'], self::$db_config['port'], self::$db_config['user'], self::$db_config['password'], self::$db_config['db_name']);
  30. }
  31. //
  32. if (in_array(2, $config)) {
  33. self::$redis_config = Config['redis'];
  34. self::$redis = new \Redis();
  35. self::$redis->pconnect(self::$redis_config['host'], self::$redis_config['port']);
  36. if (!empty(self::$redis_config['password'])) {
  37. self::$redis->auth(self::$redis_config['password']);
  38. }
  39. self::$redis->select(self::$redis_config['database']);
  40. }
  41. //
  42. // if (in_array(3, $config)) {
  43. // self::$mongodb_config = Config['mongodb'];
  44. // self::$mongo = (new MongoDB\Client(self::$mongodb_config['url']))->selectDatabase(self::$mongodb_config['database']);
  45. // }
  46. }
  47. }