zoukankan      html  css  js  c++  java
  • 翻译:Laravel-4-Generators 使用自己定义代码生成工具高速进行Laravel开发

    使用自己定义代码生成工具高速进行Laravel开发

    Build Status

    这个Laravle包提供了一种代码生成器,使得你能够加速你的开发进程。这些生成器包含:

    • generate:model – 模型生成器
    • generate:view – 视图生成器
    • generate:controller – 控制器生成器
    • generate:seed – 数据库填充器
    • generate:migration – 迁移
    • generate:pivot – 关联表
    • generate:resource -资源
    • generate:scaffold – 脚手架

    安装

    须要一个五分钟教程视频吗?

    Laravel 4.2 或者更低的版本号

    使用Composer安装这个包,编辑你项目的composer.json文件。在require中加入way/generators

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

    然后,在命令行下运行composer update:

    composer update --dev
    

    一旦这个操作完毕。就仅仅须要最后一步,在配置文件里加入服务提供者。

    打开app/config/app.php文件。加入一个新的记录到providers数组中.

    'WayGeneratorsGeneratorsServiceProvider'
    

    这样就能够了,你已经安装完毕并能够执行这个包了。

    执行artisan命令行则能够在终端上看到generate相关命令。

    php artisan
    

    Laravel 5.0 或者更高版本号

    使用Composer安装这个包,编辑你项目的composer.json文件。在require中加入way/generators

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

    因为在Laravel高版本号中默认目录结构。须要3.0或者更高的版本号。才干适应5.0版本号以上的Laravel

    然后。在命令行下运行composer update:

    composer update --dev
    

    一旦这个操作完毕,就仅仅须要最后一步,在配置文件里加入服务提供者。

    打开app/config/app.php文件,加入一个新的记录到providers数组中.

    'WayGeneratorsGeneratorsServiceProvider'
    

    这样就能够了,你已经安装完毕并能够执行这个包了。

    执行artisan命令行则能够在终端上看到generate相关命令。

    php artisan
    

    使用演示样例

    想象一下使用一个生成器加速你的工作流。

    而不是打开models目录,创建一个新的文件,保存它,而且在文件里加入一个class。你能够简单的执行一个生成器命令就可以完毕这一系列动作。

    迁移

    Laravel提供了一个迁移生成器,可是它只可以创建数据库结构。

    让我们再回想几个样例,使用generate:migration

    php artisan generate:migration create_posts_table
    

    假设我们不指定字段配置项,则以下这个文件将被创建在app/database/migrations文件夹下。

    <?php
    
    use IlluminateDatabaseMigrationsMigration;
    use IlluminateDatabaseSchemaBlueprint;
    
    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,keyword"create",意味着我们应该准备必要的架构来创建表。

    假设你使用add_user_id_to_posts_table取代迁移的名字,在上面的演示样例中。keyword"add"。意味着我们将加入一行到现有的表中,然我们看看这个生成器命令。

    php artisan generate:migration add_user_id_to_posts_table
    

    这个命令将会准备一个以下这种样板:

    <?php
    
    use IlluminateDatabaseMigrationsMigration;
    use IlluminateDatabaseSchemaBlueprint;
    
    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

    keyword

    当你在写迁移的名字的时候,使用以下的keyword给生成器提供提示。

    • create or make (create_users_table)
    • add or insert (add_user_id_to_posts_table)
    • remove (remove_user_id_from_posts_table)
    • delete or drop (delete_users_table)

    生成数据库模式

    这是很美丽的,可是让我们更进一步,生成数据库模式的同一时候。使用fields选项。

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

    在我们解释这个选项之前。让我们先看一下输出:

    <?

    php use IlluminateDatabaseMigrationsMigration; use IlluminateDatabaseSchemaBlueprint; 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选项,并加入这些字段
    • drop方法可以足够聪明的意识到。在相反的情况下,这个表应该被全然删除

    声明字段,使用逗号+空格分隔键值列表[key:value:option sets],当中key表示字段的名称,value表示字段的类型option表示制定索引或者像是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
    

    作为最后一个演示样例i,让我们执行一个迁移,从tasks表中,删除completed字段。

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

    这一次,我们使用了"remove"keyword,生成器知道它要删除一个字段,而且把它加入到down()方法中。

    <?php
    
    use IlluminateDatabaseMigrationsMigration;
    use IlluminateDatabaseSchemaBlueprint;
    
    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。假设提供的目录不存在,它会自己主动帮你创建

    Seeds 生成数据[译注:应该是用来填充測试数据]

    Laravel为我们提供了很灵活的方式来填充表 Laravel provides us with a flexible way to seed new tables.

    php artisan generate:seed users
    

    设置你想要生成的生成文件參数。这将生成 app/database/seeds/UsersTableSeeder.php 并用一下内容作为填充:

    <?

    php // Composer: "fzaninotto/faker": "v1.3.0" use FakerFactory as Faker; class UsersTableSeeder extends Seeder { public function run() { $faker = Faker::create(); foreach(range(1, 10) as $index) { User::create([ ]); } } }

    这将使用流行的Faker库为你提供一个主要的样板。这将是一个很美丽的方式来生成你的数据库表。

    不要忘记使用Composer来安装Faker。

    关联表[译注:pivot 这个词愿意是中心点、中枢的意思,这里翻译成关联表比較合适,通俗一点就是两个表的mapping关系表,带有外键约束]

    当你须要一个关联表时,generate:pivot能够加速建立对应的表。

    简单的传递两个须要关联的表的名字。对于ordersusers表。你能够:

    php artisan generate:pivot orders users
    

    这个命令将创建以下的迁移:

    <?php
    
    use IlluminateDatabaseMigrationsMigration;
    use IlluminateDatabaseSchemaBlueprint;
    
    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命令将会为你坐一系列的事情:

    • 生成一个模型
    • 生成index, show, create, edit视图
    • 生成一个控制器
    • 生成一个数据库结构迁移
    • 生成一个数据库填充
    • 迁移这个数据库

    当你触发这个命令,它将对每一个动作进行问询。通过这个方式,你能够告诉生成器,哪些是你确实须要的。

    样例

    想象假设你须要创建一个方法来显示文章。

    你须要手动创建一个控制器。一个模型,一个数据库迁移而且填充它,而且创建一个数据库填充…为什么不用生成器来做呢?

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

    假设你对每一个询问说yes。这个命令会给你例如以下样板:

    • app/models/Post.php
    • app/controllers/PostsController.php
    • app/database/migrations/timestamp-create_posts_table.php (including the schema)
    • app/database/seeds/PostsTableSeeder.php

    Scaffolding 脚手架

    脚手架生成器类似于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');
        }
    
    }
    

    请注意我们鼓舞您去改动这些自己主动生成的控制器。它仅仅是一个简单的開始。

    Configuration 配置

    你也许想改动你的模板–自己主动生成的文件是如何格式化的。考虑到这一点。你须要公布你的模板。生成器将会使用它们。

    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文件。

    这个文件看起来有点像:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    <?

    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')
     
    ];

    同一时候。当你改动这个文件的时候,注意你也能够更新每一个默认的生成器目标文件夹。

    Shortcuts 快捷命令

    由于你可能会一次重新的键入例如以下命令,命令别名显然是有意义的。

    # 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 文件里。

  • 相关阅读:
    四,iptables详解(4):iptables匹配条件总结之一
    三,iptables详解(3):iptables规则管理
    二,iptables详解(2):iptables实际操作之规则查询
    一,Iptables详解(1):iptables概念
    运维安全之Linux网络安全(iptables)
    【577】U-Net相关
    【576】Python遍历文件夹内所有文件
    【575】连续卷积层(神经网络中的通道 channel)
    【574】KDE与正态分布
    点云投影为深度图
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6727744.html
Copyright © 2011-2022 走看看