12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <?php
- declare(strict_types=1);
- namespace app\utils;
- // 引入框架内置类
- use think\facade\Db;
- use think\facade\Config;
- /**
- * 模型 utils
- *
- * @version 0.0.1
- * @author by huwhois
- * @time 2022/08/10
- */
- class ControllerUtils
- {
- protected $namespace;
- protected $class;
- protected function getPathName(string $name): string
- {
- $name = substr($name, 4);
- return app()->getBasePath() . ltrim(str_replace('\\', '/', $name), '/') . '.php';
- }
- protected function getStub(): string
- {
- return __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'controller.stub';
- }
- /**
- * 构建Class文件
- * @return string
- */
- protected function buildClass()
- {
- $stub = file_get_contents($this->getStub());
- return str_replace(['{%namespace%}', '{%className%}'], [
- $this->namespace,
- $this->class
- ], $stub);
- }
- /**
- * 生成 Model 文件
- * @param string $name 类目,包含命名空间
- * @param string $connections 数据库配置, 默认 mysql
- */
- public function makeModel(string $name, string $connections = 'mysql')
- {
- $pathname = $this->getPathName($name);
- if (is_file($pathname)) {
- throw new \Exception("Model :' . $name . ' already exists!</error>", 1);
- }
- if (!is_dir(dirname($pathname))) {
- mkdir(dirname($pathname), 0755, true);
- }
- file_put_contents($pathname, $this->codeModel($name, $connections));
- }
- /**
- * 生成 Model 不生成文件
- * @param string $name 类目,包含命名空间
- * @return string
- */
- public function codeModel(string $name)
- {
- $this->namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
- $this->class = str_replace($this->namespace . '\\', '', $name);
- return $this->buildClass();
- }
- }
|