やり方
CWebUser を継承した WebUser クラスを protected/components 下に作成し、afterLogin() メソッドを上書き (ファイル名、クラス名などは任意) 。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class WebUser extends CWebUser | |
{ | |
protected function afterLogin($fromCookie) | |
{ | |
$model = User::model()->findByPk(Yii::app()->user->id); | |
$model->last_ip = Yii::app()->request->userHostAddress; | |
$model->last_login = new CDbExpression('NOW()'); | |
$model->save(true, array('last_ip', 'last_login')); | |
} | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
... | |
'components' => array( | |
'user' => array( | |
'class' => 'WebUser', // この行を書かない場合は、デフォルトのCWebUserが使われる | |
... |
もちろん、例えばコントローラなどの actionLogin() で、バリデーションが通ったあとに、afterLogin() と同じようなコードを書くこともできますが、ログイン、ログアウト周りの実装を一元管理できる利点もあり、また CWebUser クラスには他にも、さまざまな重要な役割があるので、それをまとめてひとつのクラスファイルとして扱え、かつカスタマイズできることを考えると、使わない手はないと思います。
ただ、エクステンションの yii-user などを見ていたら、このへんを一元管理しておらず、部分部分で実装しているようです (これはおそらく v.1.1.3 になる以前に yii-user が作られたことが理由かもしれませんが) 。
0 件のコメント:
コメントを投稿