Loader.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. namespace core\loader;
  3. use Exception;
  4. use think\DbManager;
  5. use think\Facade;
  6. use think\helper\Str;
  7. abstract class Loader extends Facade
  8. {
  9. protected $config_name = null;//配置文件名
  10. protected $name = null;
  11. protected $namespace = null;
  12. protected $class = null;
  13. protected $config = null;
  14. protected $config_file = null;
  15. /**
  16. * @param string $name
  17. * @param array $config
  18. */
  19. public function __construct($name = '', array $config = [])
  20. {
  21. if (is_array($name)) {
  22. $config = $name;
  23. $name = null;
  24. }
  25. if ($name) {
  26. $this->name = $name;
  27. }
  28. $this->config = $config;
  29. }
  30. /**
  31. * 获取默认驱动
  32. * @return mixed
  33. */
  34. abstract protected function getDefault();
  35. /**
  36. * 创建实例对象
  37. * @param string $type
  38. * @return object|DbManager
  39. * @throws Exception
  40. */
  41. public function create(string $type)
  42. {
  43. $class = $this->getClass($type);
  44. return self::createFacade($class, [
  45. $this->name,
  46. $this->config,
  47. $this->config_file
  48. ], true);
  49. }
  50. /**
  51. * 获取类
  52. * @param string $type
  53. * @return mixed|string
  54. * @throws Exception
  55. */
  56. public function getClass(string $type)
  57. {
  58. $class = config($this->config_name . '.drivers.' . $type . '.driver');
  59. if (!empty($class) && class_exists($class)) {
  60. return $class;
  61. } else {
  62. if ($this->namespace || str_contains($type, '\\')) {
  63. $class = str_contains($type, '\\') ? $type : $this->namespace . $type;
  64. if (class_exists($class)) {
  65. return $class;
  66. } else {
  67. $class = str_contains($type, '\\') ? $type : $this->namespace . Str::studly($type);
  68. if (class_exists($class)) {
  69. return $class;
  70. }
  71. }
  72. }
  73. }
  74. throw new Exception("Driver [$type] not supported.");
  75. }
  76. /**
  77. * 通过装载器获取实例
  78. * @return object|DbManager
  79. * @throws Exception
  80. */
  81. public function getLoader()
  82. {
  83. if (empty($this->class)) {
  84. $this->name = $this->name ?: $this->getDefault();
  85. if (!$this->name) {
  86. throw new Exception(sprintf(
  87. 'could not find driver [%s].', static::class
  88. ));
  89. }
  90. $this->class = $this->create($this->name);
  91. }
  92. return $this->class;
  93. }
  94. /**
  95. * 动态调用
  96. * @param $method
  97. * @param $arguments
  98. * @return mixed
  99. * @throws Exception
  100. */
  101. public function __call($method, $arguments)
  102. {
  103. return $this->getLoader()->{$method}(...$arguments);
  104. }
  105. }