drawmyattention/laravel-make-resource

生成模型、迁移、控制器、路由和工厂

v1.0.0 2016-05-19 12:15 UTC

This package is not auto-updated.

Last update: 2024-09-20 19:19:50 UTC


README

Build Status Scrutinizer Code Quality codecov License

此包添加了 php artisan make:resource 命令,允许您

使用一个简单易用的命令生成模型、设置其属性、创建迁移、控制器、路由和模型工厂。

此包可以作为快速启动项目的一种方式,减少您在设置应用程序各个部分所需的时间,以便您可以专注于复杂性。

为什么使用此包?

当开始一个新项目时,我们通常会先创建一个新模型,然后进入该模型并定义其可填充属性。接下来,我们将设置迁移,并再次定义表应持有的列。

接下来,我们生成控制器,并添加 indexshoweditupdatecreatestore 方法,最后打开 routes.php 文件以设置与控制器中方法相关的端点。

如果您进行测试驱动开发或编写自动化测试,您将需要创建一个模型工厂,并再次定义相同的属性。

我发现自己一次又一次地经历同样的漫长过程,因此决定构建一个单一的命令,该命令可以

  • 创建一个模型
  • 设置其可填充和隐藏属性
  • 生成基于模型的迁移,包含列定义
  • 构建一个导入模型的RESTful控制器
  • 添加对应于模型名称的RESTful路由
  • 创建一个具有相同属性和合理的假数据的模型工厂

安装

通过Composer安装MakeResource。

"require": {
    "drawmyattention/laravel-make-resource": "~1.0"
}

接下来,更新您的 config/app.php 以将包含的服务提供者添加到 providers 数组中

'providers' => [
    // other providers
    DrawMyAttention\ResourceGenerator\ResourceGeneratorServiceProvider::class,
];

然后您就可以使用了。

使用生成器

在命令行中运行

php artisan make:resource ModelName "attributes"

对于最简单的示例,让我们创建一个新的 Animal 资源

php artisan make:resource Animal

这将创建以下内容

  • app\Animal.php
  • app\Http\Controllers\AnimalController.php
  • database\migrations\2016_05_19_090000_create_animals_table.php

以及追加到

  • app\Http\routes.php
  • database\factories\ModelFactory.php

定义模型属性

还可以为模型提供管道分隔的属性列表。例如

php artisan make:resource Animal "name:string,fillable,100,index|legs:integer,fillable,unsigned|colour|owner:hidden"

传递参数时使用的约定是,简单地使用管道分隔的列表

[属性名称]:[逗号分隔的属性]

属性顺序 不是 重要的。

如果您指定了 fillablehidden,则将相应地设置属性。如果没有提供,则不会将该属性添加到任一项中。

看看示例中的 colourowner 属性。没有提供数据类型,因此这些属性自动转换为字符串类型。

示例 Animal 模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Animal extends Model
{
    /**
     * The attributes that are used for migration generation.
     *
     * @array
     */
    protected $migrationAttributes = [
        ['name' => 'name', 'properties' => ['string', 'fillable', '100', 'index']],
        ['name' => 'legs', 'properties' => ['integer', 'fillable', 'unsigned']],
        ['name' => 'colour', 'properties' => []],
        ['name' => 'owner', 'properties' => ['hidden']]
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'legs'];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['owner'];

    /**
     * Return the attributes used to generate a migration.
     *
     * @return array
     */
    public function migrationAttributes()
    {
        return $this->migrationAttributes;
    }
}

模型已根据输入参数分配了可填充和隐藏属性。添加了一个新的 migrationAttributes 数组和获取器,这些用于生成迁移。

示例 create_animals_table.php 迁移

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAnimalsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('animals', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 100)->index();
            $table->integer('legs')->unsigned();
            $table->string('colour');
            $table->string('owner');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('animals');
    }
}

记住,make:resource 命令对于快速搭建应用程序非常有用,虽然它能让你开始,但检查迁移是否完全符合你的需求是明智的。例如,你可能希望添加更复杂的索引,这些索引不能直接从生成器添加。

示例 AnimalController.php

<?php

namespace App\Http\Controllers;

use App\Animal;
use App\Http\Requests;
use Illuminate\Http\Request;

class AnimalController extends Controller
{
    /**
     * @var Animal
     */
    private $animal;

    /**
     * @param Animal $animal
     */
    public function __construct(Animal $animal)
    {
        $this->animal = $animal;
    }

    /**
     * Return all Animals.
     *
     * @return mixed
     */
    public function index()
    {
        return $animals = $this->animal->paginate();

        // return view('animal.index', compact('animals'));
    }

    /**
     * Display a given Animal.
     *
     * @param int $id Animal identifier
     * @return mixed
     */
    public function show($id)
    {
        return $animal = $this->animal->findOrFail($id);

        // return view('animal.show', compact('animal'));
    }

    /**
     * Display the form to edit an existing Animal instance.
     *
     * @param int $id Animal identifier
     */
    public function edit($id)
    {
        $animal = $this->animal->findOrFail($id);

        // return view('animal.edit', compact('animal'));
    }

    /**
     * Update an existing Animal instance.
     *
     * @param Request $request
     */
    public function update(Request $request)
    {
        //
    }

    /**
     * Display the form to create a new Animal.
     */
    public function create()
    {
        // return view('animal.create');
    }

    /**
     * Store a new Animal.
     *
     * @param Request $request
     */
    public function store(Request $request)
    {
        // $created = $this->animal->create($request->all());

        // return redirect()->route('animal.show')->with(['id' => $created->id]);
    }

}

生成的代码定义了核心的RESTful方法,并实现了一些基本逻辑来获取和显示资源。

未来的更新还将搭建一些基本视图。

没有一些路由,控制器就没有什么价值,所以让我们看看接下来生成的路由。

app\Http\routes.php 修改

<?php

// Your existing routes remain here

/*
|--------------------------------------------------------------------------
| Animal Routes
|--------------------------------------------------------------------------
|
| Here are all routes relating to the Animal model. A restful routing naming
| convention has been used, to allow index, show, edit, update, create and
| store actions on the Animal model.
|
*/

Route::group(['prefix' => 'animal'], function () {

    Route::get('/',         ['as' => 'animal.index',    'uses' => 'AnimalController@index']);
    Route::get('/{id}',     ['as' => 'animal.show',     'uses' => 'AnimalController@show']);
    Route::get('/{id}/edit',['as' => 'animal.edit',     'uses' => 'AnimalController@edit']);
    Route::post('/update',  ['as' => 'animal.update',   'uses' => 'AnimalController@update']);
    Route::get('/create',   ['as' => 'animal.create',   'uses' => 'AnimalController@create']);
    Route::get('/store',    ['as' => 'animal.store',    'uses' => 'AnimalController@store']);

});

生成了一套整洁的路由,它与生成的控制器很好地匹配。

database\factories\ModelFactory.php

<?php

// Your existing model factories remain here

// Animal model factory

$factory->define(App\Animal::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->words(2, true),
        'legs' => $faker->randomNumber(),
        'colour' => $faker->words(2, true),
        'owner' => $faker->words(2, true),
    ];
});

需要在多个地方定义相同的属性是非常繁琐的,所以很方便地,模型工厂被自动生成,相应的伪造数据被添加到每个属性。太棒了!

限制

目前,该包假定你的应用程序位于 App 命名空间中,但未来的更新将使它更加灵活。

在模型工厂中实现 Faker 关联的方式并不真正最优 - 但它是一个好的起点。请随意分叉并提交一个PR。

运行测试

包含了一个完整的测试套件。要从包目录中执行测试

vendor/bin/phpunit tests/ResourceGeneratorTest.php

贡献

如果你发现了一个错误,或者有改进的想法,请提交一个pull-request,并附上相关的单元测试。