zorgcc / lumen-generators
Lumen 和 Laravel 5 的生成器集合。
Requires
- php: ^7.2
- fzaninotto/faker: ^1.5
- illuminate/console: ^5.1|^6
- illuminate/filesystem: ^5.1|^6
README
内容
为什么?
我安装了 Lumen,并希望用它来创建 REST API(因为这是 Lumen 的主要用途)。但我没有找到能加速我工作流程的命令。这就是我创建这个包并包含构建 RESTful API 的有用命令的原因。
这个包主要是为了与 Lumen 一起使用,但它也应该可以与 Laravel 5 一起很好地工作。
安装
通过运行以下命令将生成器包添加到您的 composer.json 中
composer require wn/lumen-generators
然后在文件 app/Providers/AppServiceProvider.php
中添加服务提供者,如下所示
public function register() { if ($this->app->environment() == 'local') { $this->app->register('Wn\Generators\CommandsServiceProvider'); } }
不要忘记在您的 bootstrap/app.php
中包含应用程序服务提供者,并且如果您正在使用 Lumen,请启用 Eloquent 和 Facades
如果您运行 php artisan list
命令,您将看到添加的命令列表
wn:controller Generates RESTful controller using the RESTActions trait
wn:controller:rest-actions Generates REST actions trait to use into controllers
wn:migration Generates a migration to create a table with schema
wn:model Generates a model class for a RESTfull resource
wn:pivot-table Generates creation migration for a pivot table
wn:resource Generates a model, migration, controller and routes for RESTful resource
wn:resources Generates multiple resources from a file
wn:route Generates RESTful routes.
快速使用
要为您应用程序生成 RESTful 资源(模型、迁移、控制器和 RESTful 路由),您只需要运行一个单独的命令。例如
php artisan wn:resource task "name;string;required;fillable project_id;integer:unsigned;numeric;fillable,key due;date;;date" --add=timestamps --belongs-to=project
将生成以下文件
app/Task.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Task extends Model { protected $fillable = ["name", "project_id"]; protected $dates = ["due"]; public static $rules = [ "name" => "required", "project_id" => "numeric", ]; public function project() { return $this->belongsTo("App\Project"); } }
app/Http/Controllers/RESTActions.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; trait RESTActions { protected $statusCodes = [ 'done' => 200, 'created' => 201, 'removed' => 204, 'not_valid' => 400, 'not_found' => 404, 'conflict' => 409, 'permissions' => 401 ]; public function all() { $m = self::MODEL; return $this->respond('done', $m::all()); } public function get($id) { $m = self::MODEL; $model = $m::find($id); if(is_null($model)){ return $this->respond('not_found'); } return $this->respond('done', $model); } public function add(Request $request) { $m = self::MODEL; $this->validate($request, $m::$rules); return $this->respond('created', $m::create($request->all())); } public function put(Request $request, $id) { $m = self::MODEL; $this->validate($request, $m::$rules); $model = $m::find($id); if(is_null($model)){ return $this->respond('not_found'); } $model->update($request->all()); return $this->respond('done', $model); } public function remove($id) { $m = self::MODEL; if(is_null($m::find($id))){ return $this->respond('not_found'); } $m::destroy($id); return $this->respond('removed'); } protected function respond($status, $data = []) { return response()->json($data, $this->statusCodes[$status]); } }
app/Http/Controllers/TasksController.php
<?php namespace App\Http\Controllers; class TasksController extends Controller { const MODEL = "App\Task"; use RESTActions; }
app/Http/routes.php
// These lignes will be added /** * Routes for resource task */ $app->get('task', 'TasksController@all'); $app->get('task/{id}', 'TasksController@get'); $app->post('task', 'TasksController@add'); $app->put('task/{id}', 'TasksController@put'); $app->delete('task/{id}', 'TasksController@remove');
database/migrations/date_time_create_tasks.php
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTasksMigration extends Migration { public function up() { Schema::create('tasks', function(Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('project_id')->unsigned(); $table->date('due'); $table->foreign('project_id') ->references('id') ->on('projects'); $table->timestamps(); }); } public function down() { Schema::drop('tasks'); } }
现在只需运行迁移即可开始。
除此之外,您还可以使用单个命令生成多个资源! 点击此处查看示例
详细使用
模型生成器
使用 wn:model
命令根据 Eloquent 生成模型类。它具有以下语法
wn:model name [--fillable=...] [--dates=...] [--has-many=...] [--has-one=...] [--belongs-to=...] [--belongs-to-many=...] [--rules=...] [--timestamps=false] [--path=...] [--soft-deletes=true] [--force=true]
- name:模型名称。
php artisan wn:model Task
生成以下内容
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Task extends Model { protected $fillable = []; protected $dates = []; public static $rules = [ // Validation rules ]; // Relationships }
- --fillable:模型的大批量可填充字段,用逗号分隔。
php artisan wn:model Task --fillable=name,title
将生成以下内容
//... protected $fillable = ['name', 'title'];
- --dates:模型的日期字段,这些字段将在检索时自动转换为
Carbon
实例。
php artisan wn:model Task --dates=started_at,published_at
将生成以下内容
//... protected $dates = ['started_at', 'published_at'];
- --path:指定存储模型 PHP 文件的路径。此路径用于确定模型的命名空间。默认值为 "app"。
php artisan wn:model Task --path="app/Http/Models"
将生成以下内容
<?php namespace App\Http\Models; //...
- --has-one,--has-many,--belongs-to 和 --belongs-to-many:模型的关联,遵循语法
relation1:model1,relation2:model2,...
。如果缺少model
,则将从关系的名称中推断出来。如果model
没有命名空间,则假定它与正在生成的模型具有相同的命名空间。
php artisan wn:model Task --has-many=accounts --belongs-to="owner:App\User" --has-one=number:Phone belongs-to-many=tags --path=tests/tmp
将生成以下内容
//... public function accounts() { return $this->hasMany("Tests\Tmp\Account"); } public function owner() { return $this->belongsTo("App\User"); } public function number() { return $this->hasOne("Tests\Tmp\Phone"); } public function tags() { return $this->belongsToMany("Tests\Tmp\Tag")->withTimestamps(); }
- --rules:指定模型字段的验证规则。语法是
field1=rules1 field2=rules2 ...
。
php artisan wn:model TestingModel --rules="name=required age=integer|min:13 email=email|unique:users,email_address"`
将生成以下内容
// ... public static $rules = [ "name" => "required", "age" => "integer|min:13", "email" => "email|unique:users,email_address", ];
-
–timestamps:启用模型的时戳。指定
–timestamps=false
将向生成的模型添加public $timestamps = false;
。默认值是true
。 -
–soft-deletes:将
Illuminate\Database\Eloquent\SoftDeletes
特性添加到模型中。默认情况下是禁用的。 -
–force:告诉生成器覆盖现有文件。默认情况下,如果模型文件已经存在,它将不会被覆盖,输出将类似于
TestingModel model already exists; use --force option to override it !
迁移生成器
wn:migration
命令用于生成创建具有模式的表的迁移。它有以下语法
wn:migration table [--schema=...] [--add=...] [--keys=...] [--force=true] [--file=...]
-
table:要创建的表名。
-
–file:迁移文件名(仅用于测试目的)。默认情况下,名称遵循模式
date_time_create_tableName_table.php
。 -
–schema:表的模式,使用语法
field1:type.arg1,ag2:modifier1:modifier2.. field2:...
。例如,type
可以是text
,string.50
,decimal.5,2
等。修饰符可以是unique
或nullable
等。有关可用类型和修饰符的列表,请参阅文档。
php artisan wn:migration tasks --schema="amount:decimal.5,2:after.'size':default.8 title:string:nullable"
将生成以下内容
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTasksMigration extends Migration { public function up() { Schema::create('tasks', function(Blueprint $table) { $table->increments('id'); $table->decimal('amount', 5, 2)->after('size')->default(8); $table->string('title')->nullable(); // Constraints declaration }); } public function down() { Schema::drop('tasks'); } }
-
–add:指定附加列,如
timestamps
、softDeletes
、rememberToken
和nullableTimestamps
。 -
–keys:表的 foreign keys,语法为
field:column:table:on_delete:on_update ...
。column
是可选的(默认为 "id")。如果字段遵循命名约定singular_table_name_id
,则table
是可选的。on_delete
和on_update
也是可选的。
php artisan wn:migration tasks --keys="category_type_id user_id:identifier:members:cascade"
将生成以下内容
//... $table->foreign('category_type_id') ->references('id') ->on('category_types'); $table->foreign('user_id') ->references('identifier') ->on('members') ->onDelete('cascade');
枢纽表生成器
wn:pivot-table
命令用于生成在两个模型之间创建枢纽表的迁移。它有以下语法
wn:pivot-table model1 model2 [--add=...] [--force=true] [--file=...]
-
model1 和 model2:两个模型(如果模型不遵循命名约定,则为两个表)的名称
-
–add:指定附加列,如
timestamps
、softDeletes
、rememberToken
和nullableTimestamps
。 -
–file:迁移文件名。默认情况下,名称遵循模式
date_time_create_table_name.php
。
php artisan wn:pivot-table Tag Project --add=timestamps
将生成以下内容
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProjectTagMigration extends Migration { public function up() { Schema::create('project_tag', function(Blueprint $table) { $table->increments('id'); $table->integer('project_id')->unsigned()->index(); $table->integer('tag_id')->unsigned()->index(); $table->foreign('project_id') ->references('id') ->on('projects'); $table->foreign('tag_id') ->references('id') ->on('tags'); $table->timestamps(); }); } public function down() { Schema::drop('project_tag'); } }
控制器生成器
有两个用于控制器的命令。第一个是 wn:controller:rest-actions
,它生成所有生成控制器使用的特性。此特性包括以下方法
-
all()
:返回所有模型条目的 JSON。 -
get($id)
:按 ID 返回特定模型作为 JSON。 -
add(Request $request)
:添加新模型或返回验证错误作为 JSON。 -
put(Request $request, $id)
:更新模型或返回验证错误作为 JSON。 -
remove($id)
:按 ID 删除条目。
请注意,特性不使用 Laravel 中常用的方法(如 index、store 等)以避免冲突。这使得您可以使用此特性与您应用程序中已有的控制器一起使用。
第二个命令是 wn:controller
,它实际上生成控制器。此命令的语法是 wn:controller model [--no-routes] [--force=true]
。
-
model:模型的名称(如果不为
App
,则包含命名空间)。 -
–no-routes:由于默认为控制器生成路由,因此此选项用于告诉生成器“不要生成路由!”。
-
–force:告诉生成器覆盖现有文件。
-
–laravel:创建 Laravel 风格的路由
php artisan wn:controller Task --no-routes
将生成以下内容
<?php namespace App\Http\Controllers; class TasksController extends Controller { const MODEL = "App\\Task"; use RESTActions; }
路由生成器
wn:route
命令用于为控制器生成 RESTful 路由。它有以下语法
wn:route resource [--controller=...] [--force=true]
-
resource:用于 URL 中的资源名称。
-
–controller:相应的控制器。如果缺失,则从资源名称推导。
-
–force:告诉生成器覆盖现有文件。
-
–laravel:创建 Laravel 风格的路由
php artisan wn:route project-type
添加以下路由
$app->get('project-type', 'ProjectTypesController@all'); $app->get('project-type/{id}', 'ProjectTypesController@get'); $app->post('project-type', 'ProjectTypesController@add'); $app->put('project-type/{id}', 'ProjectTypesController@put'); $app->delete('project-type/{id}', 'ProjectTypesController@remove');
php artisan wn:route project-type --laravel
添加以下路由
Route::get('project-type', 'ProjectTypesController@all'); Route::get('project-type/{id}', 'ProjectTypesController@get'); Route::post('project-type', 'ProjectTypesController@add'); Route::put('project-type/{id}', 'ProjectTypesController@put'); Route::delete('project-type/{id}', 'ProjectTypesController@remove');
资源生成器
wn:resource
命令使得生成 RESTful 资源变得非常容易。它生成模型、迁移、控制器和路由。语法如下:wn:resource name fields [--add=...] [--has-many=...] [--has-one=...] [--belongs-to=...] [--migration-file=...] [--path=...] [--force=true]
-
name:用于URL、模型、表和控制器命名的资源名称。
-
fields:指定资源的字段以及模式验证规则。语法为
name;schema;rules;tags ...
-
name:字段的名称
-
schema:模型生成器中遵循的语法。 (注意,名称不是模式的一部分,如模型生成器中所示)
-
rules:验证规则
-
tags:由逗号分隔的附加标签。可能的标签包括
-
fillable
:将此字段添加到模型的填充数组中。 -
date
:将此字段添加到模型的日期数组中。 -
key
:此字段是外键。
-
-
-
--add:指定迁移中额外的列,如
timestamps
、softDeletes
、rememberToken
和nullableTimestamps
。如果列表中不包含时间戳,则模型将包含public $timestamps = false;
。 -
--has-one、--has-many 和 --belongs-to 与
wn:model
命令相同。 -
--migration-file:作为
--file
选项传递给wn:migration
。 -
--path:定义存储模型文件及其命名空间的位置。
-
–force:告诉生成器覆盖现有文件。
-
–laravel:创建 Laravel 风格的路由
从文件生成多个资源
wn:resources
命令(注意 "resources" 中的 "s")通过解析文件并将多个资源基于它生成,将生成过程提升到另一个层次。语法为
wn:resources filename [--path=...] [--force=true]
此生成器足够智能,在找到 belongsTo 关系时自动添加外键。它还会自动为 belongsToMany 关系生成枢纽表。
给该命令的文件应是一个有效的 YAML 文件(目前,未来可能添加对 XML 或 JSON 等其他类型的支持)。以下是一个示例
-
--path:定义存储模型文件及其命名空间的位置。
-
–laravel:创建 Laravel 风格的路由
--- Store: hasMany: products fields: name: schema: string:50 unique rules: required|min:3 tags: fillable Product: belongsTo: store fields: name: schema: string rules: required tags: fillable store_id: schema: integer unsigned rules: required numeric tags: fillable key desc: schema: text nullable tags: fillable published_at: schema: date rules: date tags: date fillable price: schema: 'decimal:5,2' # need quotes when using ',' rules: numeric tags: fillable add: timestamps softDeletes
测试
为了测试生成器,我在 lumen-test
文件夹下包含了一个全新的 Lumen 安装,并在其中添加了此包,并使用 Codeception 编写了一些验收测试。要运行测试,只需执行 install.sh
安装依赖项,然后执行 test.sh
。
开发笔记
-
即将推出的版本
-
Seeder 和 Test 生成器
-
请求功能:[自定义模板](https://github.com/webNeat/lumen-generators/issues/13)
-
请求功能:[Fractal 集成](https://github.com/webNeat/lumen-generators/issues/24)
-
请求功能:[使用
wn:resources
时添加不运行迁移的可能性](https://github.com/webNeat/lumen-generators/issues/23) -
文档:[添加示例](https://github.com/webNeat/lumen-generators/issues/20)
-
-
版本 1.3.3
- 修复了错误:[从 YAML 文件创建资源时的规则问题](https://github.com/webNeat/lumen-generators/issues/30)
-
版本 1.3.2
- 修复了错误:[softDeletes 未添加到模型](https://github.com/webNeat/lumen-generators/issues/25)
-
版本 1.3.1
- 修复了错误:[使用
wn:resources
时外键的重复列](https://github.com/webNeat/lumen-generators/issues/22)
- 修复了错误:[使用
-
版本 1.3.0
-
请求功能:[禁用时间戳](https://github.com/webNeat/lumen-generators/issues/15)
-
请求功能:[支持 Lumen 5.3 路由](https://github.com/webNeat/lumen-generators/issues/21)
-
-
版本 1.2.0
-
修复了测试。
-
修复了错误:[未定义索引:factory](https://github.com/webNeat/lumen-generators/issues/14)
-
添加了功能:[在生成之前检查文件是否已存在](https://github.com/webNeat/lumen-generators/issues/11)
-
新增功能:支持在迁移中添加额外列,例如 nullableTimestamps() 和 softDeletes(),详情请见 GitHub 上的问题
-
新增功能:为
wn:resource
和wn:resources
指定命名空间
-
-
版本 1.1.1
- 修复了从
wn:resources
命令生成交叉表的错误。
- 修复了从
-
版本 1.1.0
-
添加了交叉表生成器。
-
模型生成器中添加了 belongsToMany 关系。
-
多资源生成器自动为 belongsTo 关系添加外键。
-
多资源生成器自动为 belongsToMany 关系添加交叉表。
-
生成的迁移文件名已更改为支持
migrate
命令。
-
-
版本 1.0.0
-
模型生成器
-
迁移生成器
-
控制器生成器
-
路由生成器
-
资源生成器
-
从文件生成多个资源
-
贡献
欢迎提交 pull request :D