---
title: "Yii框架整合Ucenter更新与增强"
author: "lonestone"
date: "2011-09-30T09:14:26Z"
tags: []
categories: ["Web前端"]
slug: "yii-ucenter"
draft: false
lastmod: "2015-12-28T11:37:20Z"
id: 1183629
url: "https://lonestone.iteye.com/blog/1183629"
---

在我前面的博文中提出了整合ucenter到yii应用的方法，还有一些不完美，那就是，登录、退出需要手动输出js到页面上来通知其他应用。那么如何做到自动处理，而不需要特别照顾？我发现只需要继承CWebUser类，实现自己的WebUser类，并覆盖登录和退出两个事件即可，不多说，上代码：

 

```
<?php
class WebUser extends CWebUser
{
    public function afterLogin($fromCookie) 
    {
		parent::afterLogin ( $fromCookie );
		
		//ucenter
		Yii::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();
		//ucenter
		Yii::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不会输出到浏览器。

 

本人博客迁移到 [http://yiidev.cn](http://yiidev.cn) 本博客停止更新