ControllerUtils.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\utils;
  4. // 引入框架内置类
  5. use think\facade\Db;
  6. use think\facade\Config;
  7. /**
  8. * 模型 utils
  9. *
  10. * @version 0.0.1
  11. * @author by huwhois
  12. * @time 2022/08/10
  13. */
  14. class ControllerUtils
  15. {
  16. protected $namespace;
  17. protected $class;
  18. protected function getPathName(string $name): string
  19. {
  20. $name = substr($name, 4);
  21. return app()->getBasePath() . ltrim(str_replace('\\', '/', $name), '/') . '.php';
  22. }
  23. protected function getStub(): string
  24. {
  25. return __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'controller.stub';
  26. }
  27. /**
  28. * 构建Class文件
  29. * @return string
  30. */
  31. protected function buildClass()
  32. {
  33. $stub = file_get_contents($this->getStub());
  34. return str_replace(['{%namespace%}', '{%className%}'], [
  35. $this->namespace,
  36. $this->class
  37. ], $stub);
  38. }
  39. /**
  40. * 生成 Model 文件
  41. * @param string $name 类目,包含命名空间
  42. * @param string $connections 数据库配置, 默认 mysql
  43. */
  44. public function makeModel(string $name, string $connections = 'mysql')
  45. {
  46. $pathname = $this->getPathName($name);
  47. if (is_file($pathname)) {
  48. throw new \Exception("Model :' . $name . ' already exists!</error>", 1);
  49. }
  50. if (!is_dir(dirname($pathname))) {
  51. mkdir(dirname($pathname), 0755, true);
  52. }
  53. file_put_contents($pathname, $this->codeModel($name, $connections));
  54. }
  55. /**
  56. * 生成 Model 不生成文件
  57. * @param string $name 类目,包含命名空间
  58. * @return string
  59. */
  60. public function codeModel(string $name)
  61. {
  62. $this->namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
  63. $this->class = str_replace($this->namespace . '\\', '', $name);
  64. return $this->buildClass();
  65. }
  66. }