CakePHP Bake でモデルを生成する
テーブル作成
まずデータベースにテーブルを作成する。
Rails ではマイグレーションを作って、マイグレーションからデータベースにテーブルを作るが、CakePHP では先にテーブルを作成する点に注意。
今回は以下のテーブルを作成する。
顧客テーブル
属性名 | 属性型 |
id | integer |
name | varchar(45) |
created | datetime |
modified | datetime |
注文テーブル
属性名 | 属性型 |
id | integer |
customer_id | integer |
title | varchar(45) |
order_code | varchar(45) |
created | datetime |
modified | datetime |
データベースを選択する
Bake を起動し M と入力すると、利用するデータベースを聞いてくる。
デフォルトのままでいい。
--------------------------------------------------------------- Bake Model Path: C:/core/work/cakeexample\app\models\ --------------------------------------------------------------- Use Database Config: (default/test) >
テーブルを選択する
選択したデータベースに存在するテーブルからモデル名が出てくる。
作成したいモデルを番号で入力する。
Possible Models based on your current database: 1. Customer 2. Order Enter a number from the list above, type in the name of another model, or 'q' to exit >
バリデーションを設定するか選択する
CakePHP では、モデルにバリデーションを実装する。
そのため、Bake でバリデーションの雛形を生成するか聞いてくる。
Would you like to supply validation criteria for the fields in your model? (y/n) >
バリデーションを選択する
フィールド名とフィールド型と共に、バリデーションが一覧で出てくる。
テーブルの情報を元にデフォルト設定をしてくれるので、大抵はデフォルトでいい。
Field: id Type: integer --------------------------------------------------------------- Please select one of the following validation options: --------------------------------------------------------------- 1 - alphaNumeric 2 - between 3 - blank
アソシエーションを設定するか選択する
CakePHP では、モデルにアソシエーションを実装する。
そのため、Bake でアソシエーションを生成するか聞いてくる。
Would you like to define model associations (hasMany, hasOne, belongsTo, etc.)? (y/n) >
アソシエーションを設定する
アソシエーションの設定を種別毎(hasMany, hasOne, belongsTo)に選択する。
テーブルの情報を元にデフォルト設定をしてくれるので、大抵はデフォルトでいい。
One moment while the associations are detected. --------------------------------------------------------------- Please confirm the following associations: --------------------------------------------------------------- Customer hasMany Order? (y/n) > Customer hasOne Order? (y/n) > Would you like to define some additional model associations? (y/n) >
モデル作成確認
上記までの操作によって生成するモデルの内容が出てくる。
内容に間違いがなければ、そのまま Enter を押す。
--------------------------------------------------------------- The following Model will be created: --------------------------------------------------------------- : : --------------------------------------------------------------- Look okay? (y/n) >
ユニット テストの作成を選択する
CakePHP は自動テストをサポートしている。
モデルに対しても自動テストができるため、自動テストコードの生成を聞いてくる。
また、自動テストには別途、SimpleTest というパッケージが必要になるため、インストールしていない場合は、メッセージが表示される。
Creating file C:/core/work/cakeexample\app\models\customer.php Wrote C:/core/work/cakeexample\app\models\customer.php SimpleTest is not installed. Do you want to bake unit test files anyway? (y/n) >
SimpleTest のインストールについては別記。
終了
Bake のメニューが出てきたら、モデルの生成は終了している。
以下に生成したファイルがある。
ROOT/app/models/model_name.php ROOT/tests/cases/modesl/model_name.test.php