[CakePHP 1.2.7]
昔からCakephpは結構使っているのでノウハウを休憩中にでもすこしずつ公開。
CGM型のWebサービスだとユーザーがなにかしらのアクションをしてDBに保存することが多いわけですが、
その際に、ユーザーを追跡出来るようにip addressを保存しておくのが普通。
Cakeでそれをやるとき、全てのmodelにipを保存するコードを書くのは面倒なので、以下のようにするとラクチン。
この場合、ip addressを保存したいテーブルにip_addressフィールド、ホスト名を保存したい場合はhost_nameフィールドを入れておく。
そしてapp_model.phpのbeforeSaveにいれておけばフィールドを追加しておいたテーブルは全て勝手に保存してくれるのであった。
app_model.php
[php]
/* fieldにip_addressがある場合は自動でipを保存 */
function afterSave($created) {
if ($created) {
if ($this->hasField(‘ip_address’)) {
$this->saveField(‘ip_address’, env(‘REMOTE_ADDR’));
}
if ($this->hasField(‘host_name’)) {
$this->saveField(‘host_name’, @gethostbyaddr(env(‘REMOTE_ADDR’)));
}
}
}
[/php]
2010/09/30
Nice tip, but you can check the existence of the field with Model::hasField($field_name).
2010/11/24
Kalt, thanks for comment.
I agree with you and it’s better to use Model::hasField($field_name) and I fixed the code.