Yii框架整合Ucenter更新与增强
在我前面的博文中提出了整合ucenter到yii应用的方法,还有一些不完美,那就是,登录、退出需要手动输出js到页面上来通知其他应用。那么如何做到自动处理,而不需要特别照顾?我发现只需要继承CWebUser类,实现自己的WebUser类,并覆盖登录和退出两个事件即可,不多说,上代码:
?
<?phpclass WebUser extends CWebUser{ public function afterLogin($fromCookie) {parent::afterLogin ( $fromCookie );//ucenterYii::import ( 'application.vendors.*' );include_once 'ucenter.php';$script = uc_user_synlogin ( $this->getId () );$count = preg_match_all ( '/src="(.+?)"/i', $script, $matches );if ($count > 0) {foreach ( $matches [1] as $file ) {Yii::app ()->clientScript->registerScriptFile ( $file, CClientScript::POS_END );}}//局部刷新顶部登录状态Yii::app()->clientScript->registerScript('refresh-login-status', 'top.$("#top_nav").load("'.CHtml::normalizeUrl(array('/site/login_status')).'");');}public function afterLogout(){parent::afterLogout();//ucenterYii::import ( 'application.vendors.*' );include_once 'ucenter.php';$script = uc_user_synlogout();$count = preg_match_all ( '/src="(.+?)"/i', $script, $matches );if ($count > 0) {foreach ( $matches [1] as $file ) {Yii::app ()->clientScript->registerScriptFile ( $file, CClientScript::POS_END );}}Yii::app()->clientScript->registerScript('refresh-login-status', 'top.$("#top_nav").load("'.CHtml::normalizeUrl(array('/site/login_status')).'");');}}
?
可以看到,我用正则匹配出了各应用通知的js,然后用CClientScript注册到页面底部。另外,由于在我的应用中头部有个局部加载的登录状态,用jquery自动更新了。
?
将这个类放在components目录下,接下来修改config/main.php的user段设置即可:
?
'user'=>array('class'=>'WebUser',// enable cookie-based authentication'allowAutoLogin'=>true,'loginUrl' => array('/site/login'),),
?
这样有个最大的好处,就是应用记住用户登录后,下次用户访问网站任何页面,都会自动登录,并同时登录到其他应用。但要注意:在用户登录成功、退出成功等action中,不要直接redirect,还是需要输出一个跳转页面,否则这些js不会输出到浏览器。
1 楼 uiexp 2012-01-09 不能直接redirect ,可以用render做一个自动跳转貌似很不错。 2 楼 yuan1238 2012-06-14 我觉得用JS做通知还是不行!还不如直接在login方法里面用curl或者socket通知