rafahsborges/laravel-4-generators

快速生成资源、迁移、模型等。

3.6 2023-08-10 18:38 UTC

This package is auto-updated.

Last update: 2024-09-10 20:58:36 UTC


README

此Laravel包提供多种生成器,以加快您的开发过程。这些生成器包括

  • generate:model
  • generate:view
  • generate:controller
  • generate:seed
  • generate:migration
  • generate:pivot
  • generate:resource
  • generate:scaffold

安装

Laravel 10

首先通过Composer安装此包。编辑您的项目 composer.json 文件以需要 way/generators

"require-dev": {
	"way/generators": "~2.0"
}

由于当前框架已经包含了许多内置生成器,因此不支持Laravel 5。

接下来,通过终端更新Composer

composer update --dev

此操作完成后,最后一步是添加服务提供者。打开 app/config/app.php,并将新项添加到提供者数组中。

'Way\Generators\GeneratorsServiceProvider'

这就完成了!您已经准备好出发了。从终端运行 artisan 命令以查看新的 generate 命令。

php artisan

接下来,通过终端更新Composer

composer update --dev

一旦此操作完成,最后一步是添加服务提供者。打开 config/app.php,并将新项添加到提供者数组中。

'Way\Generators\GeneratorsServiceProvider'

这就完成了!您已经准备好出发了。从终端运行 artisan 命令以查看新的 generate 命令。

php artisan

用法

将生成器视为一种加快您工作流程的简单方法。您不需要打开模型目录,创建新文件,保存它并添加类,只需运行单个生成命令即可。

迁移

Laravel提供了一个迁移生成器,但它仅创建模式(或表的字段)。让我们通过 generate:migration 来回顾几个例子。

php artisan generate:migration create_posts_table

如果不指定 fields 选项,将在 app/database/migrations 中创建以下文件。

<?php

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

class CreatePostsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('posts', function(Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
	}

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

}

请注意,生成器足够智能,能够检测您正在尝试创建一个表。当命名迁移时,尽可能使它们描述性。迁移生成器将检测迁移名称中的第一个单词,并尽力确定如何进行。因此,对于 create_posts_table,关键字是 "create",这意味着我们应该准备必要的模式以创建一个表。

如果您使用类似 add_user_id_to_posts_table 的迁移名称,那么关键字是 "add",表示我们打算向现有表添加行。让我们看看这会生成什么。

php artisan generate:migration add_user_id_to_posts_table

这将准备以下模板代码

<?php

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

class AddUserIdToPostsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::table('posts', function(Blueprint $table) {

        });
	}


	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
	    Schema::table('posts', function(Blueprint $table) {

        });
	}

}

请注意,这次我们没有使用 Schema::create

关键字

在编写迁移名称时,使用以下关键字为生成器提供提示。

  • createmake (create_users_table)
  • addinsert (add_user_id_to_posts_table)
  • remove (remove_user_id_from_posts_table)
  • deletedrop (delete_users_table)

生成模式

这很好,但让我们进一步,使用 fields 选项生成模式。

php artisan generate:migration create_posts_table --fields="title:string, body:text"

在解释这个新选项之前,让我们看看输出结果

<?php

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

class CreatePostsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('posts', function(Blueprint $table) {
            $table->increments('id');
            $table->string('title');
			$table->text('body');
			$table->timestamps();
        });
	}

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

}

不错!有几个要注意的地方

  • 生成器将自动将 id 设置为主键。
  • 它解析了 fields 选项,并添加了这些字段。
  • 删除方法足够智能,足以意识到反向操作应该是完全删除表。

要声明字段,请使用逗号加空格分隔的键:值:选项集列表,其中是字段的名称,列类型,而选项是指定索引等的方式,如uniquenullable。以下是一些示例

  • --fields="first:string, last:string"
  • --fields="age:integer, yob:date"
  • --fields="username:string:unique, age:integer:nullable"
  • --fields="name:string:default('John Doe'), bio:text:nullable"
  • --fields="username:string(30):unique, age:integer:nullable:default(18)"

请注意最后一个示例,我们指定了字符限制:string(30)。这将生成$table->string('username', 30)->unique();

可以通过以下命令销毁表:

php artisan generate:migration delete_posts_table

作为最后的演示,让我们运行一个迁移来从tasks表中删除completed字段。

php artisan generate:migration remove_completed_from_tasks_table --fields="completed:boolean"

这次,由于我们使用了“remove”关键字,生成器理解它应该在down()方法中删除列并重新添加。

<?php

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

class RemoveCompletedFromTasksTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::table('tasks', function(Blueprint $table) {
            $table->dropColumn('completed');
        });
	}


	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
	    Schema::table('tasks', function(Blueprint $table) {
            $table->boolean('completed');
        });
	}

}

模型

php artisan generate:model Post

这将创建文件,app/models/Post.php并插入以下模板

<?php

class Post extends \Eloquent {

}

视图

视图生成器相当简单。

php artisan generate:view admin.reports.index

此命令将创建一个空视图,/app/views/admin/reports/index.blade.php。如果提供的目录结构不存在,它将为您创建。

种子

Laravel为我们提供了一个灵活的方式来填充新表。

php artisan generate:seed users

将参数设置为需要种子文件的表名。这将生成app/database/seeds/UsersTableSeeder.php并用以下内容填充:

<?php

// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class UsersTableSeeder extends Seeder {

    public function run()
    {
        $faker = Faker::create();

        foreach(range(1, 10) as $index)
        {
            User::create([

            ]);
        }
    }

}

这将为您提供一些基本的模板,使用流行的Faker库。这是一种很好的方式来填充您的数据库表。不要忘记通过Composer引入Faker!

Pivot

当你需要新的关系表时,generate:pivot表可以加速创建适当的迁移的过程。

只需传递需要连接关系表的两个表名。对于ordersusers,你可能这样做:

php artisan generate:pivot orders users

这将创建以下迁移

<?php

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

class CreateOrderUserTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('order_user', function(Blueprint $table) {
            $table->increments('id');
			$table->integer('order_id')->unsigned()->index();
			$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
			$table->integer('user_id')->unsigned()->index();
			$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
			$table->timestamps();
        });
	}


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

}

请注意,它根据你提供的两个表正确设置了表名,按字母顺序排列。现在,运行php artisan migrate来创建你的关系表!

资源

generate:resource命令会为你做很多事情

  • 生成模型
  • 生成索引、显示、创建和编辑视图
  • 生成控制器
  • 生成包含模式的迁移
  • 生成表种子
  • 迁移数据库

在触发此命令时,你会被要求确认每个这些操作。这样,你可以根据你的具体需求调整生成过程。

示例

想象一下,你需要构建一种显示帖子的方式。虽然你可以手动创建控制器、创建模型、创建迁移并填充模式,然后创建表种子...为什么不使用生成器呢?

php artisan generate:resource post --fields="title:string, body:text"

如果你对每个确认说“是”,这个单独的命令将为你提供以下模板的模板

  • app/models/Post.php
  • app/controllers/PostsController.php
  • app/database/migrations/timestamp-create_posts_table.php(包括模式)
  • app/database/seeds/PostsTableSeeder.php

脚手架

骨架生成器与generate:resource类似,但它将为这些文件添加一些开始的模板,作为便利。

例如,当运行generate:scaffold post时,你的控制器模板将是

<?php

class PostsController extends \BaseController {

	/**
	 * Display a listing of posts
	 *
	 * @return Response
	 */
	public function index()
	{
	    $posts = Post::all();

	    return View::make('posts.index', compact('posts'));
	}

	/**
	 * Show the form for creating a new post
	 *
	 * @return Response
	 */
	public function create()
	{
        return View::make('posts.create');
	}

	/**
	 * Store a newly created post in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
	    $validator = Validator::make($data = Input::all(), Post::$rules);

	    if ($validator->fails())
	    {
	        return Redirect::back()->withErrors($validator)->withInput();
	    }

	    Post::create($data);

	    return Redirect::route('posts.index');
	}

	/**
	 * Display the specified post.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
	    $post = Post::findOrFail($id);

	    return View::make('posts.show', compact('post'));
	}

	/**
	 * Show the form for editing the specified post.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$post = Post::find($id);

		return View::make('posts.edit', compact('post'));
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$post = Post::findOrFail($id);

		$validator = Validator::make($data = Input::all(), Post::$rules);

        if ($validator->fails())
        {
            return Redirect::back()->withErrors($validator)->withInput();
        }

		$post->update($data);

		return Redirect::route('posts.index');
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		Post::destroy($id);

		return Redirect::route('posts.index');
	}

}

请注意,我们鼓励你修改这个生成的控制器。它只提供了一个起点。

配置

你可能想要修改你的模板 - 生成的文件是如何格式化的。为了允许这样做,你需要发布生成器在幕后会引用的模板。

php artisan generate:publish-templates

这将把所有模板复制到你的app/templates目录。你可以按需修改这些模板以匹配你的期望格式。如果你更喜欢不同的目录

php artisan generate:publish-templates --path=app/foo/bar/templates

当您运行 generate:publish-templates 命令时,它还将配置发布到 app/config/packages/way/generators/config/config.php。此文件看起来可能如下所示:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Where the templates for the generators are stored...
    |--------------------------------------------------------------------------
    |
    */
    'model_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/model.txt',

    'scaffold_model_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/scaffolding/model.txt',

    'controller_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/controller.txt',

    'scaffold_controller_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/scaffolding/controller.txt',

    'migration_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/migration.txt',

    'seed_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/seed.txt',

    'view_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/view.txt',


    /*
    |--------------------------------------------------------------------------
    | Where the generated files will be saved...
    |--------------------------------------------------------------------------
    |
    */
    'model_target_path'   => app_path('models'),

    'controller_target_path'   => app_path('controllers'),

    'migration_target_path'   => app_path('database/migrations'),

    'seed_target_path'   => app_path('database/seeds'),

    'view_target_path'   => app_path('views')

];

此外,当您在这个文件中时,请注意您还可以更新每个生成器的默认目标目录。

快捷键

由于您可能会反复输入这些命令,创建别名是有意义的。

# Generator Stuff
alias g:m="php artisan generate:model"
alias g:c="php artisan generate:controller"
alias g:v="php artisan generate:view"
alias g:s="php artisan generate:seed"
alias g:mig="php artisan generate:migration"
alias g:r="php artisan generate:resource"

例如,您可以将这些快捷键存储在 ~/.bash_profile~/.bashrc 文件中。