I’ve been using CakePHP a lot so I would like to release the tips little by little during break.
If it’s CGM type web service, users do some actions and keep them in DB. It’s usual to keep user’s IP addresses at that time to follow users . It takes time to write the codes in all of models to keep IP so it’ll be way easy if you do like example below.
In that case, type “ip_address” in field of the table you would like to save IP address, type also “host_name” in field if you would like to save host name.
Then keep it in “beforeSave” of app_model.php , the table you added the field will save all of IP addresses automatically.
app_model.php
/**
* save IP address automatically if DB has `ip_address` field
*/
function beforeSave() {
if ($this->hasField('ip_address') && empty($this->id) && empty($this->data[$this->alias][$this->primaryKey])) {
$this->data[$this->name]['ip_address'] = env('REMOTE_ADDR');
}
if ($this->hasField('host_name') && empty($this->id) && empty($this->data[$this->alias][$this->primaryKey])) {
$this->data[$this->name]['host_name'] = gethostbyaddr(env('REMOTE_ADDR'));
}
return true;
}
2 Comments
Nice tip, but you can check the existence of the field with Model::hasField($field_name).
Kalt, thanks for comment.
I agree with you and it’s better to use Model::hasField($field_name) and I fixed the code.
One Trackback
[...] This post was mentioned on Twitter by 長谷川 剛志, Masaya Iwata. Masaya Iwata said: Blog Updated, [CakePHP]自動でip addressやホスト名を保存する方法 http://bit.ly/aU22ZZ [...]