创建 Laravel Artisan 命令自动为每个表生成 Model Repository Service Controller

发布: (2025年12月5日 GMT+8 11:15)
3 min read
原文: Dev.to

Source: Dev.to

自定义 Artisan 命令:自动生成层

运行:

php artisan make:command GenerateCrudFromDb

实现命令

将文件 app/Console/Commands/GenerateCrudFromDb.php 替换为:

option('table');

        if (empty($tables)) {
            // If no table specified, get all tables
            $tables = $this->getAllTables();
        }

        foreach ($tables as $table) {
            $this->generateForTable($table);
        }

        $this->info('All CRUD layers generated successfully!');
    }

    protected function getAllTables()
    {
        $database = DB::getDatabaseName();
        $tables = DB::select("SHOW TABLES");
        $tables = array_map(function ($table) use ($database) {
            return $table->{'Tables_in_' . $database};
        }, $tables);
        return $tables;
    }

    protected function generateForTable($table)
    {
        $className = Str::studly(Str::singular($table));
        $modelName = $className;
        $controllerName = $className . 'Controller';
        $repositoryName = $className . 'Repository';
        $serviceName = $className . 'Service';

        $columns = $this->getTableColumns($table);

        $this->createModel($modelName, $columns);
        $this->createRepository($repositoryName, $modelName);
        $this->createService($serviceName, $repositoryName);
        $this->createController($controllerName, $serviceName);

        $this->info("CRUD generated for table: {$table}");
    }

    protected function getTableColumns($table)
    {
        $columns = DB::select("SHOW COLUMNS FROM {$table}");
        $fillable = [];
        foreach ($columns as $column) {
            if (!in_array($column->Field, ['id', 'created_at', 'updated_at', 'deleted_at'])) {
                $fillable[] = $column->Field;
            }
        }
        return $fillable;
    }

    protected function createModel($name, $fillable)
    {
        $modelPath = app_path("Models/{$name}.php");
        if (!File::exists($modelPath)) {
            $fillableArray = implode("','", $fillable);
            $content = "info("Model created: {$name}");
        }
    }

    protected function createRepository($name, $model)
    {
        $repoPath = app_path("Repositories/{$name}.php");
        if (!File::exists($repoPath)) {
            $content = "{$model} = \${$model};
    }

    public function all() { return \$this->{$model}::all(); }
    public function find(\$id) { return \$this->{$model}::find(\$id); }
    public function create(array \$data) { return \$this->{$model}::create(\$data); }
    public function update(\$id, array \$data) { 
        \$record = \$this->find(\$id); 
        if(\$record) \$record->update(\$data); 
        return \$record; 
    }
    public function delete(\$id) { 
        \$record = \$this->find(\$id); 
        if(\$record) \$record->delete(); 
        return \$record; 
    }
}
";
            File::put($repoPath, $content);
            $this->info("Repository created: {$name}");
        }
    }

    protected function createService($name, $repository)
    {
        $servicePath = app_path("Services/{$name}.php");
        if (!File::exists($servicePath)) {
            $content = "{$repository} = \${$repository};
    }

    public function all() { return \$this->{$repository}->all(); }
    public function find(\$id) { return \$this->{$repository}->find(\$id); }
    public function create(array \$data) { return \$this->{$repository}->create(\$data); }
    public function update(\$id, array \$data) { return \$this->{$repository}->update(\$id, \$data); }
    public function delete(\$id) { return \$this->{$repository}->delete(\$id); }
}
";
            File::put($servicePath, $content);
            $this->info("Service created: {$name}");
        }
    }

    protected function createController($name, $service)
    {
        $controllerPath = app_path("Http/Controllers/{$name}.php");
        if (!File::exists($controllerPath)) {
            $content = "{$service} = \${$service};
    }

    public function index() { return \$this->{$service}->all(); }
    public function store(Request \$request) { return \$this->{$service}->create(\$request->all()); }
    public function show(\$id) { return \$this->{$service}->find(\$id); }
    public function update(Request \$request, \$id) { return \$this->{$service}->update(\$id, \$request->all()); }
    public function destroy(\$id) { return \$this->{$service}->delete(\$id); }
}
";
            File::put($controllerPath, $content);
            $this->info("Controller created: {$name}");
        }
    }
}

目录结构设置

确保在你的 Laravel 项目中存在以下目录:

  • app/Models
  • app/Repositories
  • app/Services
  • app/Http/Controllers

使用方法

为数据库中的所有表生成

php artisan generate:crud

为指定表生成

php artisan generate:crud --table=customers --table=orders

该命令将自动创建:

  • 模型(Models)$fillable 根据表字段填充
  • 仓库(Repositories),实现基本的 CRUD 操作
  • 服务(Services),委托给相应的仓库
  • 控制器(Controllers),提供标准的 RESTful 行为

所有层均遵循 Repository‑Service 模式。

Back to Blog

相关文章

阅读更多 »