Laravel9 API开发,代码生成器

API代码生成器,生成的是单表的基础方法、参数规则、方法注释,复杂的还是需要后期自己加的,仅供学习用,我也是新手期。学习新的框架都按照自己的开发习惯安排:
1、分层:接口层Controller、逻辑业务层Serivcce、模型数据层 Model
2、统一格式化输出{“code”:,”data”:”msg”:};自定义报错;入参规则:校验、陈列
3、用户认证 JWT-TOKEN
4、接口授权(拦截);自动获取接口方法管理
5、redis、swagger生成、原生SQL执行、上传
6、最重要的是代码生成器、扩展

创建执行文件
app\Console\Commands\ApiGenerator.php

<?php
// 代码生成器 use App\Traits\GeneratorTemplate; use App\Traits\MysqlStructure;

namespace App\Console\Commands;

use App\Traits\GeneratorTemplate;
use App\Traits\MysqlStructure;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Symfony\Component\Console\Exception\RuntimeException;

class ApiGenerator extends Command
{
    use MysqlStructure, GeneratorTemplate;

    private $db;

    /**
     * The name and signature of the console command.
     * 控制台命令的名称和签名
     * @var string
     */
    protected $signature = 'api:generator {name} {param?}';

    /**
     * The console command description.
     * 控制台命令说明
     * @var string
     */
    protected $description = 'Create Api operations';

    public function __construct()
    {
        parent::__construct();
        $this->db = env('DB_DATABASE');
    }

    /**
     * Get the root namespace for the class.
     * 获取类的根命名空间
     * @return string
     */
    protected function rootNamespace()
    {
        return $this->laravel->getNamespace();
    }

    /**
     * Get the default namespace for the class.
     * 获取类的默认命名空间。
     * @param $name
     * @return string
     */
    protected function getDefaultNamespace($name)
    {
        return trim($this->rootNamespace(), '\\') . '\\' . $name;
    }

    /**
     * 获取规则文件
     * @param $type
     * @return bool|string
     */
    protected function getStub($type)
    {
        return file_get_contents(resource_path("stubs/$type.stub"));
    }

    /**
     * 创建控制器
     * @param $name
     */
    protected function controller($name)
    {
        $namespace = $this->getDefaultNamespace('Http\Controllers');
        $field_info = $this->getRule($this->getTableSchema($this->argument('name')));
        $controllerTemplate = $this->genControllerTemplate($namespace, $name, $field_info);
        $class = $namespace . '\\' . $name;
        if (app('files')->exists(app_path("/Http/Controllers/{$name}Controller.php"))) {
            throw new RuntimeException(sprintf('class %s exist', $class));
        }
        file_put_contents(app_path("/Http/Controllers/{$name}Controller.php"), $controllerTemplate);
        $this->info($name . ' created controller successfully.');
    }

    /**
     * 创建业务层
     * @param $name
     */
    protected function service($name)
    {
        $namespace = $this->getDefaultNamespace('Services');
        $serviceTemplate = $this->genServiceTemplate($namespace, $name);
        $class = $namespace . '\\' . $name;
        if (app('files')->exists(app_path("/Services/{$name}Service.php"))) {
            throw new RuntimeException(sprintf('class %s exist', $class));
        }
        file_put_contents(app_path("/Services/{$name}Service.php"), $serviceTemplate);
        $this->info($name . ' created service successfully.');
    }

    /**
     * 创建模型层
     * @param $name
     */
    protected function model($name)
    {
        $namespace = $this->getDefaultNamespace('Models');
        $table = Str::snake(class_basename($this->argument('name'))); // Str::pluralStudly 改表为复数
        $show_info = $this->getRule($this->getTableSchema($this->argument('name')), 1);
        $columns = $this->getTableFields($table);
        $fields = "[";
        for ($i = 0; $i < count($columns); $i++) {
            $column = $columns[$i];
            // 新增|修改字段时,过滤字段
            if (in_array($column, ["'id'", "'create_time'", "'update_time'", "'created_at'", "'updated_at'"])) {
                continue;
            }
            $fields .= sprintf("%s,", $column);
        }
        $fields .= "]";
        $fields = str_replace(",]", "]", $fields);
        $modelTemplate = $this->genModelTemplate($namespace, $name, $table, $fields, $show_info);
        $class = $namespace . '\\' . $name;
        if (app('files')->exists(app_path("/Models/{$name}.php"))) {
            throw new RuntimeException(sprintf('class %s exist', $class));
        }
        file_put_contents(app_path("/Models/{$name}.php"), $modelTemplate);
        $this->info($name . ' created model successfully.');
    }

    /**
     * Execute the console command.
     * 执行控制台命令
     * @return mixed
     */
    public function handle()
    {
        $name = Str::ucfirst($this->argument('name'));
        $name = $this->camelize($name);
        $param = $this->argument('param');
        if ($param == "c") {
            $this->controller($name);
        } else if ($param == "s") {
            $this->service($name);
        } else if ($param == "m") {
            $this->model($name);
        } else {
            $this->controller($name);
            $this->service($name);
            $this->model($name);
        }
    }

    /**
     * $type = 1 users_roles格式 变成 UsersRoles格式
     * $type = 1 users_roles格式 变成 usersRoles格式
     * @return string
     */
    public function camelize($str, $separator = '_', $type = 1)
    {
        $str = $separator . str_replace($separator, " ", strtolower($str));
        return ($type == 1) ? ucfirst(ltrim(str_replace(" ", "", ucwords($str)), $separator)) : ltrim(str_replace(" ", "", ucwords($str)), $separator);
    }

    /**
     * Convert column properties to array strings.
     * 把列的属性转化成数组的字符串
     * @return string
     */
    public function getRule($data, $type = 0)
    {
        $field_info = '';
        $show_info = '';
        $data = json_encode($data);
        $data = json_decode($data, true);
        if ($data) {
            foreach ($data as $rs) {
                // 字段属性
                if ($rs['DATA_TYPE'] == 'tinyint' || $rs['DATA_TYPE'] == 'int' || $rs['DATA_TYPE'] == 'bigint' || $rs['DATA_TYPE'] == 'smallint') {
                    $rs['DATA_TYPE'] = 'integer';
                } else if ($rs['DATA_TYPE'] == 'float' || $rs['DATA_TYPE'] == 'double') {
                    $rs['DATA_TYPE'] = 'float';
                } else if ($rs['DATA_TYPE'] == 'varchar' || $rs['DATA_TYPE'] == 'text' || $rs['DATA_TYPE'] == 'longtext') {
                    $rs['DATA_TYPE'] = 'string';
                } else if ($rs['DATA_TYPE'] == 'date' || $rs['DATA_TYPE'] == 'datetime' || $rs['DATA_TYPE'] == 'time' || $rs['DATA_TYPE'] == 'timestamp') {
                    $rs['DATA_TYPE'] = 'date';
                } else if ($rs['DATA_TYPE'] == 'json') {
                    $rs['DATA_TYPE'] = 'array';
                } else {
                    $rs['DATA_TYPE'] = 'string';
                }
                // 是否必填
                if ($rs['IS_NULLABLE'] == 'yes') {
                    $require = 'true';
                } else {
                    $require = 'false';
                }
                if ($rs['COLUMN_NAME'] == 'id') {
                    $show_info .= '                \'' . $this->camelize($rs['COLUMN_NAME'], '_', 0) . '\' => [\'type\' => \'' . $rs['DATA_TYPE'] . '\', ';
                    $show_info .= '\'description\' => \'' . $rs['COLUMN_COMMENT'] . '\'';
                    $show_info .= '], ' . PHP_EOL;
                } else {
                    if ($type == 0) {
                        if ($rs['COLUMN_NAME'] != 'create_by' && $rs['COLUMN_NAME'] != 'delete_time' && $rs['COLUMN_NAME'] != 'update_time' && $rs['COLUMN_NAME'] != 'create_time' && $rs['COLUMN_NAME'] != 'delete_at' && $rs['COLUMN_NAME'] != 'update_at' && $rs['COLUMN_NAME'] != 'create_at') {

                            $field_info .= '                \'' . $rs['COLUMN_NAME'] . '\' => [\'name\' => \'' . $rs['COLUMN_NAME'] . '\', \'type\' => \'' . $rs['DATA_TYPE'] . '\', ';
                            $field_info .= '\'require\' => ' . $require . ', ';
                            if ($rs['COLUMN_DEFAULT']) {
                                $field_info .= '\'default\' => \'' . $rs['COLUMN_DEFAULT'] . '\', ';
                            }
                            if ($rs['COLUMN_COMMENT']) {
                                $field_info .= '\'description\' => \'' . $rs['COLUMN_COMMENT'] . '\'';

                            }
                            $field_info .= '], ' . PHP_EOL;

                        }
                    } else {
                        $show_info .= '                \'' . $this->camelize($rs['COLUMN_NAME'], '_', 0) . '\' => [\'type\' => \'' . $rs['DATA_TYPE'] . '\', ';
                        if ($rs['COLUMN_DEFAULT']) {
                            $show_info .= '\'default\' => \'' . $rs['COLUMN_DEFAULT'] . '\', ';
                        }
                        if ($rs['COLUMN_COMMENT']) {
                            $show_info .= '\'description\' => \'' . $rs['COLUMN_COMMENT'] . '\'';
                        }
                        $show_info .= '], ' . PHP_EOL;
                    }
                }
            }
            return ($type) ? $show_info : $field_info;
        }
        return '';
    }

}

创建模版文件
app\Traits\GeneratorTemplate.php

<?php
namespace App\Traits;

trait GeneratorTemplate
{

    /**
     * 创建控制器模板.
     * @param $dummyNamespace
     * @param $modelName
     * @param $field_Info
     * @return string
     */
    public function genControllerTemplate($dummyNamespace, $modelName, $field_Info)
    {
        $template = <<<EOF
<?php
namespace {$dummyNamespace};

use App\Traits\ApiResponse;
use App\Services\\{$modelName}Service;
use Illuminate\Http\Request;

/**
 * {$modelName} 接口控制器
 * @desc
 */
class {$modelName}Controller extends Controller
{
    use ApiResponse;

    protected \$service;

    public function __construct()
    {
        \$this->service = new {$modelName}Service();
    }

    // 接口参数规则
    public function getRules()
    {
        return [
            'store' => [
{$field_Info}
            ],
            'destroy' => [
                'id' => ['name' => 'id', 'type' => 'integer', 'required' => true, 'description' => '主键ID'],
            ],
            'show' => [
                'id' => ['name' => 'id', 'type' => 'integer', 'required' => true, 'description' => '主键ID'],
            ],
            'update' => [
                'id' => ['name' => 'id', 'type' => 'integer', 'required' => true, 'description' => '主键ID'],
{$field_Info}
            ],
            'updateState' => [
                'ids' => ['name' => 'ids', 'type' => 'string', 'required' => true, 'description' => '主键ID組合'],
                'field' => ['name' => 'field', 'type' => 'string', 'required' => true, 'description' => '字段名称'],
                'value' => ['name' => 'value', 'type' => 'string', 'required' => true, 'description' => '字段取值'],
            ],
            'updateField' => [
                'id' => ['name' => 'id', 'type' => 'integer', 'required' => true, 'description' => '主键ID'],
                'field' => ['name' => 'field', 'type' => 'string', 'required' => true, 'description' => '字段名称'],
                'value' => ['name' => 'value', 'type' => 'string', 'required' => true, 'description' => '字段取值'],
            ],
            'list' => [],
            'index' => [
                'page' => ['name' => 'page', 'type' => 'integer', 'required' => true, 'default' => 1, 'description' => '当前页数'],
                'limit' => ['name' => 'limit', 'type' => 'integer', 'required' => true, 'default' => 20, 'description' => '每页条数'],
            ],
        ];
    }

    /**
     * {$modelName}:新增单条数据
     * @desc 权限:通用
     * @return int 新增ID
     * @method POST
     */
    public function store(Request \$request)
    {
        \$fields = verifyInputParams(\$request, \$this->getRules()['store']);
        \$result = \$this->service->store(\$fields);
        return \$this->formatUniteResult(\$result);
    }

    /**
     * {$modelName}:删除单条数据
     * @desc 权限:分配
     * @return int 影响行数
     * @method POST
     */
    public function destroy(Request \$request)
    {
        \$fields = verifyInputParams(\$request, \$this->getRules()['destroy']);
        \$result = \$this->service->destroy(\$fields);
        return \$this->formatUniteResult(\$result);
    }

    /**
     * {$modelName}:读取单条数据
     * @desc 权限:通用
     * @return array {$modelName}Model@show
     * @method GET
     */
    public function show(Request \$request)
    {
        \$fields = verifyInputParams(\$request, \$this->getRules()['show']);
        \$result = \$this->service->show(\$fields);
        return \$this->formatUniteResult(\$result);
    }

    /**
     * {$modelName}:更新单条数据
     * @desc 权限:通用,修改一行多字段值
     * @return int 影响行数
     * @method POST
     */
    public function update(Request \$request)
    {
        \$fields = verifyInputParams(\$request, \$this->getRules()['update']);
        \$result = \$this->service->update(\$fields);
        return \$this->formatUniteResult(\$result);
    }

    /**
     * {$modelName}:更新单列批量
     * @desc 权限:通用,修改单行|多行的某字段的状态值
     * @return int 影响行数
     * @method POST
     */
    public function updateState(Request \$request)
    {
        \$fields = verifyInputParams(\$request, \$this->getRules()['updateState']);
        \$result = \$this->service->updateState(\$fields);
        return \$this->formatUniteResult(\$result);
    }

    /**
     * {$modelName}:更新单列单条
     * @desc 权限:通用,修改某记录某字段的值
     * @return int 影响行数
     * @method POST
     */
    public function updateField(Request \$request)
    {
        \$fields = verifyInputParams(\$request, \$this->getRules()['updateField']);
        \$result = \$this->service->updateField(\$fields);
        return \$this->formatUniteResult(\$result);
    }

    /**
     * {$modelName}:列表记录数据
     * @desc 权限:通用,多用于下拉数据, 集合:不分页
     * @return array {$modelName}Model@list
     * @method GET
     */
    public function list(Request \$request)
    {
        \$fields = verifyInputParams(\$request, \$this->getRules()['list']);
        \$result = \$this->service->list(\$fields);
        return \$this->formatUniteResult(\$result);
    }

    /**
     * {$modelName}:全部列表数据
     * @desc 权限:通用,集合:带分页
     * @return array {$modelName}Model@index
     * @method GET
     */
    public function index(Request \$request)
    {
        \$fields = verifyInputParams(\$request, \$this->getRules()['index']);
        \$result = \$this->service->index(\$fields);
        return \$this->formatUniteResult(\$result);
    }

}
EOF;
        return $template;
    }

    /**
     * 创建服务模板.
     * @param $dummyNamespace
     * @param $modelName
     * @return string
     */
    public function genServiceTemplate($dummyNamespace, $modelName)
    {
        $template = <<<EOF
<?php
namespace {$dummyNamespace};

use Eloquence\Behaviours\CamelCasing;
use App\Models\\{$modelName};

/**
 * {$modelName} 业务逻辑
 */
class {$modelName}Service
{
    // throw new \App\Exceptions\BusinessException(400, '自定义异常错误处理');
    use CamelCasing;

    protected \$model;

    public function __construct()
    {
        \$this->model = new {$modelName}();
    }

    // 新增数据 Model层 \$fillable要加上
    public function store(\$forms = [])
    {
        return \$this->model::insertGetId(\$forms);  // ID
        // return \$this->model::create(\$forms);    // REQUEST+ID 建议用于新增后插入或者更新
        // return \$this->model::insert(\$forms);    // TRUE | FALSE 建议用于多条插入
    }

    // 删除数据 Model层 \$fillable要加上delete_time | deleted_at
    public function destroy(\$forms = [])
    {
        \$where = ['id' => \$forms['id']];
        \$param = ['delete_time' => time()];
        return \$this->model->where(\$where)->update(\$param); // 软删除
        // return \$this->model::destroy(\$where); // 直删除
    }

    // 读取数据
    public function show(\$forms = [])
    {
        \$data = \$this->model->where(\$forms)->first(); // 用于多条件
        // \$data = \$this->model::findOrFail(\$forms['id']); // 用于ID条件
        return listArrayAllowKeys(\$data, \$this->model->getRules()['show']);
    }

    // 更新多列单条 Model层 \$fillable要存在对应的字段
    public function update(\$forms = [])
    {
        \$where = ['id' => \$forms['id']];
        return \$this->model::where(\$where)->update(\$forms); // 用于多条件 // id不存在,return 0;
        // return \$this->model::findOrFail(\$forms['id'])->update(\$forms); // 用于ID条件 // id不存在时, return 报错信息
    }

    /**
    * 更新单列多条
    * Model层 \$fillable要存在对应的更新字段
    */
    public function updateState(\$forms = [])
    {
        \$ids = explode(',', \$forms['ids']);
        \$field = \$forms['field']; // 字段名称
        \$value = \$forms['value']; // 字段赋值
        \$param = [\$field => \$value];
        return \$this->model::whereIn('id', \$ids)->update(\$param);
    }

    /**
    * 更新单列单条
    * Model层\$fillable要存在对应的更新字段
    */
    public function updateField(\$forms = [])
    {
        \$id = \$forms['id'];
        \$field = \$forms['field']; // 字段名称
        \$value = \$forms['value']; // 字段赋值
        \$param = [\$field => \$value];
        return \$this->model::where('id', \$id)->update(\$param);
    }

    // 列表数据
    public function list(\$forms = [])
    {
        return listArrayAllowKeys(\$this->model->index(\$forms), \$this->model->getRules()['list']);
    }

    // 分页数据
    public function index(\$forms = [])
    {
        return listArrayAllowKeys(\$this->model->index(\$forms), \$this->model->getRules()['index']);
    }

    // 检查字段值是否存在
    private function check(\$field, \$param)
    {
        \$result = \$this->model::where(\$field, \$param)->first();
        if (\$result) {
            throw new \App\Exceptions\BusinessException(400, \$field . '=' . \$param . '已经存在');
        }
    }

    /**
    * 获取字段值 \$select = 'name'
    * 获取整行值 \$select = '*'
    */
    private function getDataBy(\$field, \$param, \$select)
    {
        \$result = \$this->model::where(\$field, \$param)->first();
        if (!isset(\$select) || \$select == '*') {
            return \$result;
        } else {
            return \$result ? \$result[\$select] : '';
        }
    }
}

EOF;
        return $template;
    }

    /**
     * 创建模型模板.
     * @param $dummyNamespace 命名空间
     * @param $modelName 模型名
     * @param $tableName 表名
     * @param $fields
     * @return string
     */
    public function genModelTemplate($dummyNamespace, $modelName, $tableName, $fields, $show_info)
    {

        $template = <<<EOF
<?php
namespace {$dummyNamespace};

// use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Eloquence\Behaviours\CamelCasing;

/**
 * {$modelName} 数据模型
 */
class {$modelName} extends Model
{
    //throw new \App\Exceptions\BusinessException(400, '自定义异常错误处理');
    use CamelCasing;

    protected \$table = '{$tableName}';
    protected \$fillable = {$fields}; // 增改时允许赋值字段(白名单)
    protected \$guarded = ['id']; // 增改时禁止赋值字段(黑名单)
    protected \$hidden = []; // 列表时隐藏的字段
    protected \$appends = []; // 需要追加的字段
    protected \$casts = []; // 字段类型转换 ['字段名' => '自动类型转换的目标类型'];
    protected \$attributes = []; // 字段赋予默认值 ['字段名' => '字段默认值']
    public \$timestamps = false;

    // 列表数据
    public function list(\$forms = [])
    {
        \$query = self::query();
        \$query->select(\$this->table . '.*');
        \$query->where(\$this->table . '.delete_time', 0);
        return \$query->get();
    }

    // 分页数据
    public function index(\$forms = [])
    {
        // ** 传入参数处理 **
        \$keyword = isset(\$forms['keyword'])?\$forms['keyword']:'';

        // ** 执行SQL语句 **
        \$query = self::query();

        // 列名
        \$select = [\$this->table . '.*'];

        // 条件
        // \$query->where(\$this->table . '.delete_time', 0); // isset(\$forms['param']) && \$query->where(\$this->table . '.x',  \$forms['param']);

        // WHEN 条件 //\$keyword 需要判断isset
        //\$query->when(\$keyword, function (\$query) use (\$keyword) {
        //    \$query->where(function (\$query) use (\$keyword) {
        //        \$query->Where(\$this->table . '.x', 'like', '%' . \$keyword . '%');
        //        \$query->orWhere(\$this->table . '.y', 'like', '%' . \$keyword . '%');
        //    });
        //});

        // 左查询
        // \$query->leftJoin('T', \$this->table . '.x', '=', 'T.id');

        // 排序
        \$query->orderByDesc(\$this->table . '.id'); // \$query->orderBy(\$this->table . '.id', 'desc');

        // 分页
        return \$query->Paginate(\$forms['limit'], \$select, 'page', \$forms['page']);

        // SQL
        // return \$query->toSql();

    }

    // 接口参数规则
    public function getRules()
    {
        return [
            'show' => [
$show_info
            ],
            'list' => [
$show_info
            ],
            'index' => [
                'data' => [
                    'type' => 'array',
                    'description' => '用户数据',
                    'items' => [
                        '\$ref' => "#/definitions/UsersModel@common",
                    ],
                ],
                'count' => [
                    'type' => 'integer',
                    'description' => '总条数',
                ],
            ],
            'common' => [
$show_info
            ],
        ];
    }

}

EOF;
        return $template;
    }
}

创建扫码数据表字段文件,部分代码是自己写的getTableSchema,大部分代码抄别的大神的
\app\Traits\MysqlStructure.php

<?php
namespace App\Traits;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Console\Exception\RuntimeException;

trait MysqlStructure
{

    private $db;

    private $database;

    private $doctrineTypeMapping = [
        'tinyint' => 'boolean',
        'smallint' => 'smallint',
        'mediumint' => 'integer',
        'int' => 'integer',
        'integer' => 'integer',
        'bigint' => 'bigint',
        'tinytext' => 'text',
        'mediumtext' => 'text',
        'longtext' => 'text',
        'text' => 'text',
        'varchar' => 'string',
        'string' => 'string',
        'char' => 'string',
        'date' => 'date',
        'datetime' => 'datetime',
        'timestamp' => 'datetime',
        'time' => 'time',
        'float' => 'float',
        'double' => 'float',
        'real' => 'float',
        'decimal' => 'decimal',
        'numeric' => 'decimal',
        'year' => 'date',
        'longblob' => 'blob',
        'blob' => 'blob',
        'mediumblob' => 'blob',
        'tinyblob' => 'blob',
        'binary' => 'binary',
        'varbinary' => 'binary',
        'set' => 'simple_array',
        'json' => 'json',
    ];

    /**
     * 表字段类型替换成laravel字段类型
     * @param string $table
     * @return Collection
     */
    public function tableFieldsReplaceModelFields(string $table): Collection
    {
        $sql = sprintf('SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = \'%s\' AND TABLE_NAME = \'%s\' ',
            $this->getDatabase(), $table);
        $columns = collect(DB::select($sql));
        if ($columns->isEmpty()) {
            throw new RuntimeException(sprintf('Not Found Table, got "%s".', $table));
        }
        $columns = $columns->map(function ($column) {
            if ($column && $column->DATA_TYPE) {
                if (array_key_exists($column->DATA_TYPE, $this->doctrineTypeMapping)) {
                    $column->DATA_TYPE = $this->doctrineTypeMapping[$column->DATA_TYPE];
                }
            }
            return $column;
        });
        return $columns;
    }

    /**
     * 获取数据库所有表
     * @return array
     */
    protected function getAllTables()
    {
        $tables = DB::select('show tables');
        $box = [];
        $key = 'Tables_in_' . $this->db;
        foreach ($tables as $tableName) {
            $tableName = $tableName->$key;
            $box[] = $tableName;
        }
        return $box;
    }

    /**
     * 输出表信息
     * @param $tableName
     */
    protected function outTableAction($tableName)
    {
        $columns = $this->getTableColumns($tableName);
        $rows = [];
        foreach ($columns as $column) {
            $rows[] = [
                $column->COLUMN_NAME,
                $column->COLUMN_TYPE,
                $column->COLUMN_DEFAULT,
                $column->IS_NULLABLE,
                $column->EXTRA,
                $column->COLUMN_COMMENT,
            ];
        }
        $header = ['COLUMN', 'TYPE', 'DEFAULT', 'NULLABLE', 'EXTRA', 'COMMENT'];
        $this->table($header, $rows);
    }

    /**
     * 输出某个表所有字段
     * @param $tableName
     * @return mixed
     */
    public function getTableFields($tableName)
    {
        $columns = collect($this->getTableColumns($tableName));
        $columns = $columns->pluck('COLUMN_NAME');
        $columns = $columns->map(function ($value) {
            return "'{$value}'";
        });
        return $columns->toArray();
    }

    /**
     * 获取数据库的表名
     * @param $table
     * @return array
     */
    public function getTableColumns($table)
    {
        $sql = sprintf('SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = \'%s\' AND TABLE_NAME = \'%s\' ',
            $this->getDatabase(), $table);
        $columns = DB::select($sql);
        if (!$columns) {
            throw new RuntimeException(sprintf('Not Found Table1, got "%s".', $table));
        }
        return $columns;
    }

    /**
     * 获取表注释
     * @param $table
     * @return string
     */
    public function getTableComment($table)
    {
        $sql = sprintf('SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = \'%s\' AND TABLE_SCHEMA = \'%s\'',
            $table, $this->getDatabase());
        $tableComment = DB::selectOne($sql);
        if (!$tableComment) {
            return '';
        }
        return $tableComment->TABLE_COMMENT;
    }

    /**
     * 获取表字段注释
     * @author wilson lee
     * @param $table
     * @return string
     */
    public function getTableSchema($table)
    {
        $sql = sprintf('SELECT tb.TABLE_COMMENT, col.TABLE_NAME, col.COLUMN_NAME, col.COLUMN_DEFAULT, col.IS_NULLABLE, col.DATA_TYPE, col.COLUMN_TYPE, col.EXTRA,col.COLUMN_COMMENT FROM INFORMATION_SCHEMA.TABLES tb INNER JOIN INFORMATION_SCHEMA.COLUMNS col ON tb.TABLE_NAME = col.TABLE_NAME WHERE tb.TABLE_NAME = \'%s\' AND tb.TABLE_SCHEMA = \'%s\' AND col.TABLE_SCHEMA = \'%s\' ',
            $table, $this->getDatabase(), $this->getDatabase());
        return DB::select($sql);
    }

    public function getDatabase()
    {
        return env('DB_DATABASE');
    }
}

运行代码:

php artisan api:generator categories c 
php artisan api:generator categories s 
php artisan api:generator categories m
  • c 只生成控制器层
  • s 只生成业务逻辑层
  • m 只生成模型层
    什么也不加 php artisan api:generator categories 生成3个文件

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 2

不錯,很好的東西

1个月前 评论

给个建议,一键生成功能,利用框架自带的生成助手集成到你封装的脚本即可;例如controller/model,框架本身就带了这样的命令,而且功能也比较齐全,没必要再撸一遍,只是service/repository,可能需要手撸一遍,如果二者没有特定的功能封装,基本上就是一个普通类的封装,完全可以共用一套生成方法。

1个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!