4-3 はじめての bake

4-3 では bake というコードのひな形を作ってくれるらしいツールの使い方を勉強していくようです。まあ、使えば分かるでしょうから、さっさと進みます。

4-2 では、Windows 環境の話がつらつらと書いてあったんですが、Mac には全く関係がないのでスルーしました。

うちの MAMP の場合、cake というフォルダ名で /Applications/MAMP/htdocs に配置したので、/Applications/MAMP/htdocs/cake/cake/console/cake に存在して、app フォルダは、/Applications/MAMP/htdocs/cake/app ということになります。

[cci_bash]
/Applications/MAMP/htdocs/cake/cake/console/cake bake -app /Applications/MAMP/htdocs/cake/app
[/cc]

というわけで、長ったらしいですが、実行して見ます。早速 warning がでました。

Warning: strtotime(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘Asia/Tokyo’ for ‘JST/9.0/no DST’ instead in /Applications/MAMP/htdocs/cake/cake/libs/cache.php on line 429

PHP 5 からタイムゾーンの設定をしてやらないと、ゴニョゴニョうるさいんで、設定してやります。まず、ひな形をコピーします。

[cc_bash]
sudo cp /etc/php.ini.default /etc/php.ini
sudo vi /etc/php.ini
[/cc]

date.timezone が ; でコメントアウトされているので、以下のように Asia/Tokyo に書き換えます。

[cc_php]
[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = Asia/Tokyo
[/cc]

上記は、Mac OS X 10.6 の Snow Leopard に始めから入っている php (cli) の設定方法で、MAMP の php (cli) を使う方法ではありませんので、念のため。

ちょっと脱線したので、bake の勉強に戻り、/path/to/cake bake -app /path/to/app を実行します。今度は上手く bake の画面が表示されました。4-3-1 です。

[cc]
Welcome to CakePHP v1.2.6 Console
—————————————————————
App : app
Path: /Applications/MAMP/htdocs/cake/app
—————————————————————
Interactive Bake Shell
—————————————————————
[D]atabase Configuration
[M]odel
[V]iew
[C]ontroller
[P]roject
[Q]uit
What would you like to Bake? (D/M/V/C/P/Q)
>
[/cc]

4-3-2 に進んで、モデルを作ります。すっかりすっ飛ばしてますけど、MVC についてはそれなり理解している(とかってに思っている)ので、イチイチ確認しません。もっとも、Cocoa のそれと、CakePHP のそれが全く同じではないと思いますけど。

とうわけで、M を選択して進もうとすると、またもやエラー。

PHP Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///var/mysql/mysql.sock) in /Applications/MAMP/htdocs/cake/cake/libs/model/datasources/dbo/dbo_mysql.php on line 454

php.ini で mysql 関連も設定しないといけないようです。以下のように書き換えました。

[cc]
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
; http://php.net/mysql.default-socket
;mysql.default_socket = /var/mysql/mysql.sock
mysql.default_socket = /Applications/MAMP/tmp/mysql/mysql.sock
[/cc]

今度はうまく行き、次の画面に遷移できました。

[cc]
—————————————————————
Bake Model
Path: /Applications/MAMP/htdocs/cake/app/models/
—————————————————————
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
[q] >
[/cc]

1 を入力して、Customer のひな形を作ってもらうことにします。
最初に validation について尋ねてくるので、適宜選択しました。

[cc]
Would you like to supply validation criteria for the fields in your model? (y/n)
[y] >

Field: id
Type: integer
—————————————————————
Please select one of the following validation options:
—————————————————————
1 – alphaNumeric
2 – between
(中略)
28 – userDefined
29 – Do not do any validation on this field.
… or enter in a valid regex validation string.

[29] >
[/cc]

次に、アソシエーションについて質問されるので、適宜選択しました。

[cc]
Would you like to define model associations (hasMany, hasOne, belongsTo, etc.)? (y/n)
[y] >
One moment while the associations are detected.
—————————————————————
Please confirm the following associations:
—————————————————————
Customer hasMany Order? (y/n)
[y] >
Customer hasOne Order? (y/n)
[y] > n
Would you like to define some additional model associations? (y/n)
[n] > n
[/cc]

最後に、確認がでるので、test は無視してひな形を作成してもらいます。

[cc]
—————————————————————
The following Model will be created:
—————————————————————
Name: Customer
Validation: Array
(
[name] => notempty
[tel] => phone
)

Associations:
Customer hasMany Order
—————————————————————
Look okay? (y/n)
[y] >
[/cc]

実際に作成されたファイルは、app/models/customer.php で以下のような内容でした。

[cc_php]
array(‘notempty’),
‘tel’ => array(‘phone’)
);

//The Associations below have been created with all possible keys, those that are not needed can be removed
var $hasMany = array(
‘Order’ => array(
‘className’ => ‘Order’,
‘foreignKey’ => ‘customer_id’,
‘dependent’ => false,
‘conditions’ => ”,
‘fields’ => ”,
‘order’ => ”,
‘limit’ => ”,
‘offset’ => ”,
‘exclusive’ => ”,
‘finderQuery’ => ”,
‘counterQuery’ => ”
)
);

}
?>[/cc]

4-3-6 に進んで、OrderRecord クラス、自分の場合は、改名したので Order クラスの作成を始めます。validation で order_date が「date」という提案がなされましたが、date 型でも time 型でもなく、datetime 型なので、29 を選択しました。結果、app/models/order.php が以下の内容で作成されました。

[cc]
array(
‘className’ => ‘Customer’,
‘foreignKey’ => ‘customer_id’,
‘conditions’ => ”,
‘fields’ => ”,
‘order’ => ”
)
);

}
?>
[/cc]

4-3-7 に進み、コントローラを作成します。

[cc]
—————————————————————
Bake Controller
Path: /Applications/MAMP/htdocs/cake/app/controllers/
—————————————————————
Possible Controllers based on your current database:
1. Customers
2. Orders
Enter a number from the list above, type in the name of another controller, or ‘q’ to exit
[q] > 1
—————————————————————
Baking CustomersController
—————————————————————
Would you like to build your controller interactively? (y/n)
[y] > n
Would you like to include some basic class methods (index(), add(), view(), edit())? (y/n)
[y] >
Would you like to create the methods for admin routing? (y/n)
[y] > n

—————————————————————
The following controller will be created:
—————————————————————
Controller Name: Customers
—————————————————————
Look okay? (y/n)
[y] > y

Creating file /Applications/MAMP/htdocs/cake/app/controllers/customers_controller.php
Wrote /Applications/MAMP/htdocs/cake/app/controllers/customers_controller.php
SimpleTest is not installed. Do you want to bake unit test files anyway? (y/n)
[y] > n
[/cc]

以上の操作で、app/controllers/customers_controller.php が次の内容で作成されました。
同様に、orders_controller.php も作成しました。

[cc_php]
Customer->recursive = 0;
$this->set(‘customers’, $this->paginate());
}

function view($id = null) {
if (!$id) {
$this->Session->setFlash(__(‘Invalid Customer’, true));
$this->redirect(array(‘action’ => ‘index’));
}
$this->set(‘customer’, $this->Customer->read(null, $id));
}

function add() {
if (!empty($this->data)) {
$this->Customer->create();
if ($this->Customer->save($this->data)) {
$this->Session->setFlash(__(‘The Customer has been saved’, true));
$this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(__(‘The Customer could not be saved. Please, try again.’, true));
}
}
}

function edit($id = null) {
if (!$id && empty($this->data)) {
$this->Session->setFlash(__(‘Invalid Customer’, true));
$this->redirect(array(‘action’ => ‘index’));
}
if (!empty($this->data)) {
if ($this->Customer->save($this->data)) {
$this->Session->setFlash(__(‘The Customer has been saved’, true));
$this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(__(‘The Customer could not be saved. Please, try again.’, true));
}
}
if (empty($this->data)) {
$this->data = $this->Customer->read(null, $id);
}
}

function delete($id = null) {
if (!$id) {
$this->Session->setFlash(__(‘Invalid id for Customer’, true));
$this->redirect(array(‘action’ => ‘index’));
}
if ($this->Customer->del($id)) {
$this->Session->setFlash(__(‘Customer deleted’, true));
$this->redirect(array(‘action’ => ‘index’));
}
$this->Session->setFlash(__(‘The Customer could not be deleted. Please, try again.’, true));
$this->redirect(array(‘action’ => ‘index’));
}

}
?>
[/cc]

4-3-10 に進みます。今度は、ビューを作ります。作成されたファイルは以下の通りです。.ctp という拡張子のファイルは、中身は普通の html というか、php スクリプトでした。

[cc]
—————————————————————
Bake View
Path: /Applications/MAMP/htdocs/cake/app/views/
—————————————————————
Possible Controllers based on your current database:
1. Customers
2. Orders
Enter a number from the list above, type in the name of another controller, or ‘q’ to exit
[q] > 1
Would you like to create some scaffolded views (index, add, view, edit) for this controller?
NOTE: Before doing so, you’ll need to create your controller and model classes (including associated models). (y/n)
[n] > y
Would you like to create the views for admin routing? (y/n)
[y] > n

Creating file /Applications/MAMP/htdocs/cake/app/views/customers/index.ctp
Wrote /Applications/MAMP/htdocs/cake/app/views/customers/index.ctp

Creating file /Applications/MAMP/htdocs/cake/app/views/customers/view.ctp
Wrote /Applications/MAMP/htdocs/cake/app/views/customers/view.ctp

Creating file /Applications/MAMP/htdocs/cake/app/views/customers/add.ctp
Wrote /Applications/MAMP/htdocs/cake/app/views/customers/add.ctp

Creating file /Applications/MAMP/htdocs/cake/app/views/customers/edit.ctp
Wrote /Applications/MAMP/htdocs/cake/app/views/customers/edit.ctp
—————————————————————

View Scaffolding Complete.
[/cc]

4-3-12 に進みます。早くも動作チェック。で、早速コケました。

validation で phone を指定したんですが、日本の電話番号が通りません。validation.php の実装を見ると、/^(?:\+?1)?[-. ]?\\(?[2-9][0-8][0-9]\\)?[-. ]?[2-9][0-9]{2}[-. ]?[0-9]{4}$/ にマッチさせています。コメントにある通りですが、NANPA というらしい北米の電話番号フォーマットに合致するか確認していて、日本の電話番号はもちろんこれには合致しないケースがあります。ということで、とりあえず、phone はコメントアウトして、動作しないように変更しました。

[cc_php]
/**
* Check that a value is a valid phone number.
*
* @param mixed $check Value to check (string or array)
* @param string $regex Regular expression to use
* @param string $country Country code (defaults to ‘all’)
* @return boolean Success
* @access public
*/
function phone($check, $regex = null, $country = ‘all’) {
$_this =& Validation::getInstance();
$_this->check = $check;
$_this->regex = $regex;
$_this->country = $country;
if (is_array($check)) {
$_this->_extract($check);
}

if (is_null($_this->regex)) {
switch ($_this->country) {
case ‘us’:
// includes all NANPA members. see http://en.wikipedia.org/wiki/North_American_Numbering_Plan#List_of_NANPA_countries_and_territories
default:
$_this->regex = ‘/^(?:\+?1)?[-. ]?\\(?[2-9][0-8][0-9]\\)?[-. ]?[2-9][0-9]{2}[-. ]?[0-9]{4}$/’;
break;
}
}
return $_this->_check();
}
[/cc]

それと、もう一つ間違えていたのは、以下のスクリーンショットの赤丸の部分が最初表示されなかった。

原因は、ビューを作る際に、y とするべきところをそのまま n で進んでいたため、scaffolded view というものが作成されていなかったようだ。再度 bake でビューを作成し、上書きすることで解決できた。

[cc]
Would you like to create some scaffolded views (index, add, view, edit) for this controller?
NOTE: Before doing so, you’ll need to create your controller and model classes (including associated models). (y/n)
[n] > y
[/cc]

にほんブログ村 ライフスタイルブログ 薪ストーブ暮らしへ
にほんブログ村 ライフスタイルブログ 薪ストーブ暮らしに参加しています。 励みになりますので、足あとがわりに、ランクアップにご協力下さい。

Leave a Reply