flickerleap/lumen-generators

Lumen和Laravel 5生成器的集合。

1.4.0 2018-01-30 09:56 UTC

This package is not auto-updated.

Last update: 2024-09-23 07:05:44 UTC


README

Build Status Scrutinizer Code Quality SensioLabsInsight License

LumenLaravel 5提供的生成器集合。

内容

为什么?

我安装了Lumen并想用它来创建REST API(因为这是Lumen的主要用途)。但我没有找到可以加快我工作流程的命令。这就是我创建这个包并包含构建RESTful API的有用命令的原因。

这个包主要是为了与Lumen一起使用而构建的,但它也应该与Laravel 5很好地工作。

安装

通过运行以下命令将生成器包添加到您的composer.json中

composer require flickerleap/lumen-generators

然后在文件app/Providers/AppServiceProvider.php中添加服务提供者,如下所示

public function register()
{
    if ($this->app->environment() == 'local') {
        $this->app->register('FlickerLeap\Generators\CommandsServiceProvider');
    }
}

别忘了在您的bootstrap/app.php中包含应用程序服务提供者,并且如果您使用Lumen,请启用Eloquent和Facades

如果您运行命令php artisan list,您将看到添加的命令列表

flickerleap:controller               Generates RESTful controller using the RESTActions trait
flickerleap:controller:rest-actions  Generates REST actions trait to use into controllers
flickerleap:migration                Generates a migration to create a table with schema
flickerleap:model                    Generates a model class for a RESTfull resource
flickerleap:pivot-table              Generates creation migration for a pivot table
flickerleap:resource                 Generates a model, migration, controller and routes for RESTful resource
flickerleap:resources                Generates multiple resources from a file
flickerleap:route                    Generates RESTful routes.

快速使用

要为您的应用程序生成RESTful资源(模型、迁移、控制器和RESTful路由),您只需运行一个命令即可。例如

php artisan flickerleap: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');
    }
}

现在只需运行迁移即可。

除此之外,您还可以通过一个命令生成多个资源! 点击此处查看示例

详细使用

模型生成器

flickerleap:model命令用于根据Eloquent生成模型类。它有以下语法

flickerleap: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 flickerleap: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 flickerleap:model Task --fillable=name,title给出

//...	
	protected $fillable = ['name', 'title'];
  • --dates:模型的日期字段,这些字段在检索时将自动转换为Carbon实例。

php artisan flickerleap:model Task --dates=started_at,published_at给出

//...	
	protected $dates = ['started_at', 'published_at'];
  • --path:指定存储模型PHP文件的路径。此路径用于确定模型的命名空间。默认值是“app”。

php artisan flickerleap: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 flickerleap: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 flickerleap: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 !

迁移生成器

flickerleap:migration命令用于生成创建具有模式的表的迁移。它有以下语法

flickerleap: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可以是textstring.50decimal.5,2。修饰符可以是uniquenullable等。有关可用类型和修饰符的列表,请参阅[文档](https://laravel.net.cn/docs/5.1/migrations#creating-columns)。

php artisan flickerleap: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:指定额外的列,如timestampssoftDeletesrememberTokennullableTimestamps

  • --keys:表的表外键,语法为field:column:table:on_delete:on_update ...column是可选的(默认为“id”)。如果字段遵循命名约定singular_table_name_id,则table是可选的。on_deleteon_update也是可选的。

php artisan flickerleap: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');

枢纽表生成器

flickerleap:pivot-table命令用于生成迁移,以在两个模型之间创建枢纽表。它有以下语法

flickerleap:pivot-table model1 model2 [--add=...] [--force=true] [--file=...]
  • model1model2:两个模型(如果模型不遵循命名约定,则是两个表)的名称。

  • --add:指定额外的列,如timestampssoftDeletesrememberTokennullableTimestamps

  • --file:迁移文件名。默认情况下,名称遵循date_time_create_table_name.php模式。

php artisan flickerleap: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');
    }
}

控制器生成器

有两个控制器命令。第一个是flickerleap:controller:rest-actions,它生成所有生成控制器使用的特质。这个特质包括以下方法

  • all():返回所有模型条目作为JSON。

  • get($id):按id返回特定的模型作为JSON。

  • add(Request $request):添加新的模型或返回验证错误作为JSON。

  • put(Request $request, $id):更新模型或返回验证错误作为JSON。

  • remove($id):按id删除条目。

请注意,特质不使用Laravel中常用的方法(如index、store等)以避免冲突。这使得您可以将此特质与您应用程序中已有的控制器一起使用。

第二个命令是flickerleap:controller,它实际上生成控制器。该命令的语法是flickerleap:controller model [--no-routes] [--force=true]

  • model:模型的名称(如果不在App中,则带有命名空间)。

  • --no-routes:由于默认为控制器生成路由,因此此选项用于告诉生成器“不要生成路由!”。

  • --force:告诉生成器覆盖现有文件。

  • --laravel:创建Laravel风格的路线

php artisan flickerleap:controller Task --no-routes生成以下内容

<?php namespace App\Http\Controllers;


class TasksController extends Controller {

	const MODEL = "App\\Task";

	use RESTActions;

}

路由生成器

flickerleap:route命令用于为控制器生成RESTful路由。它有以下语法

flickerleap:route resource [--controller=...] [--force=true]

  • resource:要在URL中使用的资源名称。

  • --controller:相应的控制器。如果缺失,则从资源名称中推断。

  • --force:告诉生成器覆盖现有文件。

  • --laravel:创建Laravel风格的路线

php artisan flickerleap: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 flickerleap: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');

资源生成器

flickerleap:resource命令使生成RESTful资源变得非常简单。它生成模型、迁移、控制器和路由。语法如下:flickerleap:resource name fields [--add=...] [--has-many=...] [--has-one=...] [--belongs-to=...] [--migration-file=...] [--path=...] [--force=true]

  • 名称:用于URLs以及确定模型、表和控制器名称的资源名称。

  • 字段:指定资源的字段,包括模式和验证规则。其语法为name;schema;rules;tags ...

    • name:字段的名称

    • schema:模型生成器中遵循的语法。注意,名称不是模式的一部分,如模型生成器所示。

    • rules:验证规则

    • tags:由逗号分隔的额外标签。可能的标签包括

      • fillable:将此字段添加到模型的填充数组。

      • date:将此字段添加到模型的日期数组。

      • key:此字段是外键。

  • --add:指定迁移中如timestampssoftDeletesrememberTokennullableTimestamps等额外列,如果列表中没有时间戳,则模型将包含public $timestamps = false;

  • --has-one--has-many--belongs-toflickerleap:model命令相同。

  • --migration-file:作为--file选项传递给flickerleap:migration

  • --path:定义模型文件的存储位置及其命名空间。

  • --force:告诉生成器覆盖现有文件。

  • --laravel:创建Laravel风格的路线

从文件生成多个资源

flickerleap:resources(注意“resources”中的“s”)命令通过解析文件并基于它生成多个资源,将生成过程提升到另一个层次。其语法为

flickerleap: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

开发笔记

贡献

欢迎提交pull request :D