macromindonline / 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的生成器集合。
内容
为什么?
我安装了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和< strong>--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:表的外键,语法为
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 名称 字段 [--add=...] [--has-many=...] [--has-one=...] [--belongs-to=...] [--migration-file=...] [--path=...] [--force=true]
-
名称:资源在 URL 中使用的名称,用于确定模型、表和控制器名称。
-
字段:指定资源的字段,包括模式和验证规则。其语法为
名称;模式;规则;标签 ...
-
名称:字段的名称
-
模式:遵循模型生成器中语法的模式。(注意,名称不是模式的一部分,就像在模型生成器中一样)
-
规则:验证规则
-
标签:由逗号分隔的额外标签。可能的标签有
-
fillable
:将此字段添加到模型的 fillable 数组中。 -
date
:将此字段添加到模型的 dates 数组中。 -
key
:此字段是外键。
-
-
-
--add:指定迁移中额外的列,如
timestamps
、softDeletes
、rememberToken
和nullableTimestamps
。如果列表中不包含时间戳,则模型将包含public $timestamps = false;
。 -
--has-one、--has-many 和 --belongs-to 与
wn:model
命令相同。 -
--migration-file:作为
wn:migration
的--file
选项传递。 -
--path:定义模型文件的存储位置以及其命名空间。
-
–force:告诉生成器覆盖现有文件。
-
–laravel:创建 Laravel 风格的路由
从文件生成多个资源
wn:resources
命令(注意 "resources" 中的 "s")通过解析文件并将多个资源基于它生成,将生成过程提升到另一个层次。其语法如下
wn:resources filename [--path=...] [--force=true]
此生成器足够智能,当找到 belongsTo 关系时,会自动添加外键。它还会自动为 belongsToMany 关系生成 pivot 表。
提供给命令的文件应该是有效的 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
。
开发说明
-
即将推出的版本
-
Seeds 和 Test 生成器
-
请求的功能:自定义模板
-
请求的功能:Fractal 集成
-
文档:添加示例
-
-
版本 1.3.3
- 错误修复:从 YAML 文件创建资源时的规则问题
-
版本 1.3.2
- 错误修复:softDeletes 没有添加到模型中
-
版本 1.3.1
-
版本 1.3.0
-
请求的功能:禁用时间戳
-
请求的功能:支持 Lumen 5.3 路由
-
-
版本 1.2.0
-
测试修复。
-
错误修复:未定义索引:factory
-
新增功能:在生成前检查文件是否已存在
-
-
版本 1.1.1
- 从
wn:resources
命令生成交叉表的错误已修复。
- 从
-
版本 1.1.0
-
新增交叉表生成器。
-
模型生成器中添加了 belongsToMany 关系。
-
多资源生成器自动为 belongsTo 关系添加外键。
-
多资源生成器自动为 belongsToMany 关系添加交叉表。
-
生成的迁移文件名已更改,以支持
migrate
命令。
-
-
版本 1.0.0
-
模型生成器
-
迁移生成器
-
控制器生成器
-
路由生成器
-
资源生成器
-
从文件生成多个资源
-
贡献
欢迎提交拉取请求 :D