## 使用自定義代碼生成工具快速進行Laravel開發
這個Laravle包提供了一種代碼生成器,使得你可以加速你的開發進程,這些生成器包括:
* generate:model – 模型生成器
* generate:view – 視圖生成器
* generate:controller – 控制器生成器
* generate:seed – 數據庫填充器
* generate:migration – 遷移
* generate:pivot – 關聯表
* generate:resource -資源
* generate:scaffold – 腳手架
項目地址
> https://github.com/laracasts/Laravel-5-Generators-Extended
## 安裝
#### 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`數組中.
~~~
'Way\Generators\GeneratorsServiceProvider'
~~~
這樣就可以了,你已經安裝完成并可以運行這個包了。運行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`數組中.
~~~
'Way\Generators\GeneratorsServiceProvider'
~~~
這樣就可以了,你已經安裝完成并可以運行這個包了。運行artisan命令行則可以在終端上看到`generate`相關命令。
~~~
php artisan
~~~
## 使用示例
想象一下使用一個生成器加速你的工作流。而不是打開models文件夾,創建一個新的文件,保存它,并且在文件中添加一個class,你可以簡單的運行一個生成器命令即可完成這一系列動作。
* Migrations 遷移
* Models 模型
* Views 視圖
* Seeds 填充
* Pivot 關聯表
* Resources 資源
* Scaffolding 腳手架
* Configuration 配置
#### 遷移
Laravel提供了一個遷移生成器,但是它僅僅能夠創建數據庫結構。讓我們再回顧幾個例子,使用`generate:migration`。
~~~
php artisan generate:migration create_posts_table
~~~
如果我們不指定字段配置項,則下面這個文件將被創建在`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
#### 關鍵字
當你在寫遷移的名字的時候,使用下面的關鍵字給生成器提供提示。
* 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 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`選項,并添加這些字段
* drop方法能夠足夠聰明的意識到,在相反的情況下,這個表應該被完全刪除
聲明字段,使用逗號+空格分隔鍵值列表[`key:value:option sets`],其中`key`表示字段的名稱,`value`表示字段的類型,`option`表示制定索引或者像是`unique`、`nullable`這樣的屬性。 這里是一些示例:
* --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`"關鍵字,生成器知道它要刪除一個字段,并且把它添加到`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`。如果提供的文件夾不存在,它會自動幫你創建
`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 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 這個詞愿意是中心點、中樞的意思,這里翻譯成關聯表比較合適,通俗一點就是兩個表的mapping關系表,帶有外鍵約束]
當你需要一個關聯表時,`generate:pivot`可以加速建立相應的表。
簡單的傳遞兩個需要關聯的表的名字。對于`orders`和`users`表,你可以:
~~~
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`命令將會為你坐一系列的事情:
* 生成一個模型
* 生成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`文件。這個文件看起來有點像:
~~~
<?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` 文件中。
* * * * *
原文地址:[http://www.huyanping.cn/?p=364](http://www.huyanping.cn/?p=364)
- 前言
- 發行說明/L5新特性
- 升級向導
- 升級到 5.0.16
- 從 4.2 升級到 5.0
- 從 4.1 升級到 4.2
- 從 4.1.x 升級到 4.1.29
- 從 4.1.25 升級到 4.1.26
- 從 4.0 升級到 4.1
- 貢獻向導
- 環境配置
- 安裝
- 配置
- 基本功能
- 路由
- 基本路由
- CSRF 保護
- 方法欺騙
- 路由參數
- 命名路由
- 路由群組
- 路由模型綁定
- 拋出 404 錯誤
- 中間件
- 建立中間件
- 注冊中間件
- 可終止中間件
- 控制器
- 基礎控制器
- 控制器中間件
- 隱式控制器
- RESTful 資源控制器
- 請求
- 取得請求實例
- 取得輸入數據
- 舊輸入數據
- Cookies
- 上傳文件
- 其他的請求信息
- 響應
- 基本響應
- 重定向
- 其他響應
- 響應宏
- 系統架構
- 服務提供者
- 基本提供者例子
- 注冊提供者
- 緩載提供者
- 服務容器
- 基本用法
- 將接口綁定到實現
- 上下文綁定
- 標簽
- 實際應用
- 容器事件
- 參考:理解PHP 依賴注入|Laravel IoC容器
- Contracts
- 為什么用 Contracts
- Contract 參考
- 如何使用 Contracts
- Facades
- 實際用法
- 建立 Facades
- 模擬 Facades
- Facade 類參考
- 請求的生命周期
- 生命周期概要
- 聚焦于服務提供者
- 應用程序結構
- 根目錄
- App 目錄
- 為應用程序配置命名空間
- 系統服務
- 認證
- 用戶認證
- 取得經過認證的用戶
- 保護路由
- HTTP 基本認證
- 忘記密碼與重設
- 第三方登陸認證
- 交易
- 配置文件
- 訂購方案
- 一次性付款
- Single Charges
- 免信用卡試用
- 訂購轉換
- 訂購數量
- 取消訂購
- 恢復訂購
- 確認訂購狀態
- 處理失敗訂閱
- 處理其它 Stripe Webhooks
- 收據
- 緩存
- 配置
- 緩存用法
- 遞增與遞減
- 緩存標簽
- 緩存事件
- 數據庫緩存
- 集合
- Command Bus
- 建立命令
- 調用命令
- 命令隊列
- 命令管道
- 核心擴展
- 管理者和工廠
- 緩存
- Session
- 認證
- 基于服務容器的擴展
- Laravel Elixir
- 安裝與配置
- 使用方式
- Gulp
- Custom Tasks and Extensions
- 加密
- Envoy 任務執行器
- 安裝
- 執行任務
- 多服務器
- 并行執行
- 任務宏
- 通知
- 更新 Envoy
- 錯誤與日志
- 配置
- 錯誤處理
- HTTP 異常
- 日志
- 事件
- 基本用法
- 事件處理隊列
- 事件訂閱者
- 文件系統與云存儲
- 配置文件
- 基本用法
- 自定義文件系統
- 哈希
- 基本用法
- 輔助方法
- 數組
- 路徑
- 路由
- 字符串
- 網址(URL)
- 其他
- 本地化
- 語言文件
- 基本用法
- 復數
- 驗證
- 覆寫擴展包的語言文件
- 郵件
- 配置
- 基本用法
- 內嵌附件
- 郵件隊列
- 郵件與本地端開發
- 擴展包開發
- 視圖
- 語言
- 配置文件
- 公共資源
- 發布分類文件
- 路由
- 分頁
- 配置
- 使用
- 追加分頁鏈接
- 轉換至 JSON
- 隊列
- 設置
- 基本用法
- 隊列閉包
- 執行一個隊列監聽
- 常駐隊列處理器
- 推送隊列
- 已失敗的工作
- 會話
- 配置
- 使用 Session
- 暫存數據(Flash Data)
- 數據庫 Sessions
- Session 驅動
- 模板
- Blade 模板
- Blade 控制語法結構
- Blade 擴展
- 參考:@section與@yield 介紹
- 單元測試
- 定義并執行測試
- 測試環境
- 從測試調用路由
- 模擬 Facades
- 框架 Assertions
- 輔助方法
- 重置應用程序
- 表單驗證
- 基本用法
- 控制器驗證
- 表單請求驗證
- 使用錯誤信息
- 錯誤信息 & 視圖
- 可用驗證規則
- 條件驗證規則
- 自定義錯誤信息
- 自定義驗證規則
- 數據庫
- 使用基礎
- 配置
- 讀取/寫入連接
- 執行查找
- 數據庫事務處理
- 獲取連接
- 日志記錄
- 查詢構造器
- Selects
- Joins
- 高級 Wheres
- 聚合
- 原生表達式
- 添加
- 更新
- 刪除
- Unions
- 悲觀鎖定 (Pessimistic Locking)
- Eloquent ORM
- 基本用法
- 批量賦值
- 新增,更新,刪除
- 軟刪除
- 時間戳
- 范圍查詢
- Global Scopes
- 關聯
- 關聯查詢
- 預載入
- 新增關聯模型
- 更新上層時間戳
- 使用樞紐表
- 集合
- 獲取器和修改器
- 日期轉換器
- 屬性類型轉換
- 模型事件
- 模型觀察者
- 模型 URL 生成
- 轉換成數組 / JSON
- 結構生成器
- 建立與刪除數據表
- 加入字段
- 修改字段
- 修改字段名稱
- 移除字段
- 檢查是否存在
- 加入索引
- 外鍵
- 移除索引
- 移除時間戳記和軟刪除
- 保存引擎
- 遷移和數據填充
- 建立遷移文件
- 執行遷移
- 回滾遷移
- 數據填充
- Redis
- 配置
- 使用方式
- 管道
- 開發包
- Confide 用戶身份認證
- Entrust 權限管理
- Shoppingcart 購物車
- Genertators 代碼生成工具
- IDE Helper IDE助手
- Artisan 命令行工具
- 概覽
- 用法
- 在命令行接口以外的地方調用命令
- 定時調用 Artisan 命令
- 開發
- 建立自定義命令
- 注冊自定義命令