diff --git a/app/command/DiygwApiCommand.php b/app/command/DiygwApiCommand.php new file mode 100644 index 0000000000000000000000000000000000000000..d00386a8c24ac4d3543029c45f3d04a771524993 --- /dev/null +++ b/app/command/DiygwApiCommand.php @@ -0,0 +1,183 @@ + +// +---------------------------------------------------------------------- + +declare (strict_types = 1); + +namespace app\command; + + +use think\console\Input; +use think\console\Output; +use think\facade\Db; +use think\helper\Str; + +class DiygwApiCommand extends DiygwMakeCommand +{ + protected $type = "Controller"; + + private $table = ''; + + protected $columns = []; + + protected $notUpdateColumn = ['create_time', 'update_time', 'create_by', 'update_by', 'delete_time', 'id']; + + protected function configure() + { + parent::configure(); + // 指令配置 + $this->setName('diygw:api') + ->setDescription('创建表相关Api等类'); + } + + + protected function getStub(): string + { + return __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'api_controller.stub'; + } + + protected function getNamespace(string $app): string + { + return parent::getNamespace($app) . '\\'.strtolower($this->type); + } + + protected function getClassName(string $name): string + { + if (strpos($name, '\\') !== false) { + return $name; + } + + if (strpos($name, '@')) { + [$app, $name] = explode('@', $name); + if($this->type=='Model'){ + $name = ucfirst($app).ucfirst($name); + $app = "common"; + $this->module = $app."_"; + } + } + + $app = ''; + if (strpos($name, '/') !== false) { + $name = str_replace('/', '\\', $name); + } + + return $this->getNamespace($app) . '\\' . $name; + } + + protected function getPathName(string $name): string + { + $name = substr($name, 4); + + return $this->app->getBasePath() . ltrim(str_replace('\\', '/', $name), '/') .ucfirst($this->type). '.php'; + + } + + protected function getTable($name) + { + $table = ''; + + if (strpos($name, '@')) { + [$table, $c] = explode('@', $name); + } + return $table; + } + + protected function getColumn($table) + { + $sth = Db::connect()->getPDOStatement(sprintf('select * from `%s` limit 1', $table)); + if ($sth === false) { + return []; + } + $columns = []; + for($i=0; $i < $sth->columnCount(); $i++) { + $meta = $sth->getColumnMeta($i); + $name = $meta['name'] ?? ''; + if (empty($name)) { + throw new \Exception('获取数据库字段失败'); + } + $native_type = $meta['native_type'] ?? ''; + $columns[$name] = array( + 'name' => $name, + 'native_type' => $native_type, + 'type' => in_array($native_type, ['VAR_STRING', 'BLOB', 'DATETIME']) ? 'STR' : 'INT', + ); + } + return $columns; + + } + + protected function buildClass(string $name) + { + $stub = file_get_contents($this->getStub()); + + $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\'); + + $class = str_replace($namespace . '\\', '', $name); + + $postParamStr = ''; + $insertStr = ''; + foreach ($this->columns as $val) { + if (in_array($val['name'], $this->notUpdateColumn)) { + continue; + } + if ($val['type'] == 'INT') { + $parse = 'd'; + $default = '0'; + } else { + $parse = 's'; + $default = '\'\''; + } + $postParamStr .= sprintf('$%s = $this->request->post(\'%s/%s\', %s);%s', $val['name'], $val['name'], $parse, $default, "\n"); + $insertStr .= sprintf('\'%s\' => $post[\'%s\'] ?? %s,%s', $val['name'], $val['name'], $default, "\n\t\t\t"); + } + $insertStr = rtrim($insertStr); + + + return str_replace(['{%className%}','{%classNameLower%}','{%year%}','{%module%}', '{%actionSuffix%}', '{%namespace%}', '{%app_namespace%}', '{%tableName%}', '{%postParamStr%}', '{%insertStr%}'], [ + $class, + Str::snake($class,"_"), + date('Y'), + $this->module, + $this->app->config->get('route.action_suffix'), + $namespace, + $this->app->getNamespace(), + $this->table, + $postParamStr, + $insertStr, + ], $stub); + } + + protected function execute(Input $input, Output $output) + { + $this->type = 'Controller'; + + $name = trim($input->getArgument('name')); + + $this->table = $this->getTable($name); + + $this->columns = $this->getColumn($this->table); + + $classname = $this->getClassName($name); + + $pathname = $this->getPathName($classname); + + if (is_file($pathname)) { + $output->writeln('' . $this->type . ':' . $classname.ucfirst($this->type) . ' already exists!'); + return false; + } + + if (!is_dir(dirname($pathname))) { + mkdir(dirname($pathname), 0755, true); + } + + file_put_contents($pathname, $this->buildClass($classname)); + + $output->writeln('' . $this->type . ':' . $classname.ucfirst($this->type) . ' created successfully.'); + return true; + } +} diff --git a/app/command/stubs/api_controller.stub b/app/command/stubs/api_controller.stub new file mode 100644 index 0000000000000000000000000000000000000000..e231a466bc070f0d83d83ed000f186c52f1b3e40 --- /dev/null +++ b/app/command/stubs/api_controller.stub @@ -0,0 +1,105 @@ + +// +---------------------------------------------------------------------- +declare (strict_types = 1); + +namespace {%namespace%}; + +use app\BaseController; +use think\facade\Db; + +/** + * @mixin \diygw\model\DiygwModel + * @package {%namespace%} + */ +class {%className%}Controller extends BaseController +{ + //是否显示所有数据 + public $isAll = false; + //是否初始化模型 + public $isModel = false; + //判断是否全部不需要登录 + public $notNeedLoginAll = false; + //判断不需要登录的方法 + public $notNeedLogin = []; + + public function save() + { + $post = $this->request->post(); + $data = array( + {%insertStr%} + ); + $data['update_by'] = $this->userId; + $id = $post['id'] ?? 0; + if (empty($id)) { + $data['create_by'] = $this->userId; + $ret = Db::table('{%tableName%}')->insertGetId($data); + $id = $ret; + } else { + $ret = Db::table('{%tableName%}')->where('id', $id)->update($data); + } + if ($ret === false) { + return $this->error('保存失败'); + } + return $this->successData(['id' => $id], '保存成功'); + } + + public function get() + { + $id = $this->request->get('id/d', 0); + $data = Db::table('{%tableName%}')->where('id', $id)->find(); + if (empty($data)) { + return $this->error('记录不存在'); + } + return $this->successData($data); + } + + public function list() + { + $page = $this->request->get('page/d', 1); + $size = $this->request->get('size/d', 10); + $all = $this->request->get('all/d', 0); //是否查询全部 + $query = Db::table('{%tableName%}') + ->where('delete_time', 'null'); + $total = $query->count(); + $ret = [ + 'total' => $total, + 'list' => [], + ]; + if ($total == 0) { + return $this->successData($ret); + } + $query = $query->order('id', 'asc'); + if (!$all) { + $start = ($page - 1) * $size; + $query = $query->limit($start, $size); + } + $list = $query->select()->toArray(); + if (!$ret) { + return $this->successData($ret); + } + //列表处理 + + $ret['list'] = $list; + return $this->successData($ret); + } + + public function del() + { + $id = $this->request->post('id/d', 0); + if (empty($id)) { + return $this->error('参数错误'); + } + $ret = Db::table('{%tableName%}')->where('id', $id)->update(['delete_time' => date('Y-m-d H:i:s'), 'update_by' => $this->userId]); + if ($ret === false) { + return $this->error('删除失败'); + } + return $this->success(); + } + +} diff --git a/config/console.php b/config/console.php index 68e96e3bb200d0309188a20c1ed0c7f25d496f9b..153b12002cee23382326f954bf1188493da2509d 100644 --- a/config/console.php +++ b/config/console.php @@ -12,5 +12,6 @@ return [ 'diygw:model' => 'app\command\DiygwModelCommand', 'diygw:validate' => 'app\command\DiygwValidateCommand', 'diygw:wechat' => 'app\command\DiygwWechatCommand', + 'diygw:api' => 'app\command\DiygwApiCommand', ], ]; diff --git a/update/20221026/default.sql b/update/20221026/default.sql new file mode 100644 index 0000000000000000000000000000000000000000..4b955f0a5792b282f2145cb97d0de1c853c0c7ab --- /dev/null +++ b/update/20221026/default.sql @@ -0,0 +1,9 @@ +-- 建表基础字段 + +alter table `sys_test` + add `create_by` varchar(128) NOT NULL DEFAULT '' COMMENT '创建人', + add `update_by` varchar(128) NOT NULL DEFAULT '' COMMENT '更新人', + add `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + add `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + add `delete_time` datetime DEFAULT NULL COMMENT '删除时间'; + diff --git a/update/20221026/readme.md b/update/20221026/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..75583c0a6049afba86ba125ada1a7b04445d9601 --- /dev/null +++ b/update/20221026/readme.md @@ -0,0 +1,12 @@ +根据表结构自动生成增删查改接口 + +自建表需包含 default.sql 文件中默认字段 + +1.数据库中建表 + +2.命令: php think diygw:api {表名}@{controller名} 将自动生成list get save del 接口 + +例: +``` +php think sys_user@SysUser +``` \ No newline at end of file