wn / lumen-generators
Lumen 和 Laravel 5 的生成器集合。
Requires
- php: >=5.5.0
- fzaninotto/faker: ^1.5
- illuminate/console: ^5.1
- illuminate/filesystem: ^5.1
README
Lumen 和 Laravel 5 的生成器集合,用于创建 RESTful API。
内容
为什么?
我安装了 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]
- 名称:模型的名称。
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
。 -
–软删除:将
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=...]
-
表名:要创建的表名。
-
–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:表的外键,语法为
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 的资源名称,以及确定模型、表和控制器名称。
-
字段:指定资源的字段以及模式验证规则。其语法为
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
- 错误修复:[软删除未添加到模型](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(),详情请见此处
-
新增功能:为
wn:resource
和wn:resources
指定命名空间
-
-
版本 1.1.1
- 修复了从
wn:resources
命令生成数据透视表的错误。
- 修复了从
-
版本 1.1.0
-
添加了数据透视表生成器。
-
在模型生成器中添加了 belongsToMany 关系。
-
多资源生成器自动添加 belongsTo 关系的外键。
-
多资源生成器自动添加 belongsToMany 关系的数据透视表。
-
生成的迁移文件名已更改,以支持
migrate
命令。
-
-
版本 1.0.0
-
模型生成器
-
迁移生成器
-
控制器生成器
-
路由生成器
-
资源生成器
-
从文件生成多个资源
-
贡献
欢迎提交 pull request :D