首页 > 代码库 > YII MVC之用户注册和用户登录(一)

YII MVC之用户注册和用户登录(一)

这部分主要包含

1 基本控制器、模型、视图使用规则;

2 登录和注册在视图通过表单使用YII小物件并分析;

3 模型中规则制定和分析;

4 控制器用方法形式访问其他类;

5 进行session和cookie分析 ,并在前后区分session和cookie;

6 生成验证码 ;

这期间也会会有错误,会不断修正

先看下目录结构:


1 基本控制器、模型、视图使用规则;

控制器:都需要继承Controller基类  进行外部访问的方法都需要以action做为方法名称的开始。

用方法形式访问其他类,需要定义actions方法,返回一个二维数组

模型:继承CActiveRecord,基本要实现:四个方法,一个是model,是静态public类型,用来返回模型名称,

一个talbeName,用来返回方法名称;

一个是attributeLabels,设置显示内容,将前面视图中英文转化为汉字,进行统一管理

一个是rules,设置一些验证规则

视图:主要是通过小物件来实现,$this -> beginWidget(‘CActiveForm‘);

此篇把主要贴下来,下面再进行调用讲解

前台控制器:

<?php
/**
 * 用户控制器
 */
class UserController extends Controller{
    /*
     * 验证码生成
     * 以下代码的意思:在当前控制器里边,以方法的形式访问其他类
     * 我们访问./index.php?r=user/captcha就会访问到以方法的CCaptchaAction
     *          会走CCaptchaAction类里边的run()方法
     * 
     * 谁会过来使用 user/captcha 这个路由
     * 答:是视图表单间接过来调用($this->widget('CCaptcha'))
     */
    function actions(){
        return array(
            'captcha'=>array(
                'class'=>'system.web.widgets.captcha.CCaptchaAction',
                'width'=>75,
                'height'=>30,
            ),
            
            //我们在外边随便定义一个类,都可以通过这种方式访问
            // user/co 就会访问Computer.php里边的run()方法
            'co'=>array(
                'class'=>'application.controllers.Computer',
            ),
        );
    }
    
    /**
     *用户登录 
     */
    function actionLogin(){
        echo $this -> id."<br />";
        echo $this -> action->id;
        
        //创建登录模型对象
        $user_login = new LoginForm;
        
        if(isset($_POST['LoginForm'])){
            //收集表单信息
            $user_login->attributes = $_POST['LoginForm'];
            
            //校验数据,走的是rules()方法
            //该地方不只校验用户名和密码是否填写,还要校验真实性(在模型里边自定义方法校验真实性)
            //用户信息进行session存储,调用模型里边的一个方法login(),就可以进行session存储
            
            if($user_login->validate() && $user_login->login()){
                $this ->redirect ('./index.php');
            }
        }
        
        $this -> render('login',array('user_login'=>$user_login));
    }
    
    /*
     * 实现用户注册功能:
     * 1. 展现注册表单
     * 2. 收集数据、校验数据、存储数据
     */
    function actionRegister(){
        //实例化数据模型对象user
        $user_model = new User();
        /**
         * renderPartial不渲染布局
         * render会渲染布局 
         */
        //$this ->renderPartial('register');
        
        //性别信息
        $sex[1] = "男";
        $sex[2] = "女";
        $sex[3] = "保密";
        
        //定义学历
        $xueli[1] = "-请选择-";
        $xueli[2] = "小学";
        $xueli[3] = "初中";
        $xueli[4] = "高中";
        $xueli[5] = "大学";
        
        //定义爱好信息
        $hobby[1] = "篮球";
        $hobby[2] = "足球";
        $hobby[3] = "排球";
        $hobby[4] = "棒球";
        
        //如果用户有注册表单
        if(isset($_POST['User'])){
            //给模型收集表单信息
            //foreach($_POST['User'] as $_k => $_v){
            //    $user_model -> $_k = $_v;
            //}
            
            //收集转化爱好的信息implode
            if(is_array($_POST['User']['user_hobby']))
                $_POST['User']['user_hobby'] = implode(',',$_POST['User']['user_hobby']);
            
            //密码要md5加密
            $_POST['User']['password'] = md5($_POST['User']['password']);
            $_POST['User']['password2'] = md5($_POST['User']['password2']);
            
            //上边的foreach,在yii框架里边有优化,使用模型属性attributes来进行优化
            //attributes 属性已经把foreach集成好了,我们可以直接使用
            $user_model -> attributes = $_POST['User'];
            
            //实现信息存储
            if($user_model -> save())
                $this ->redirect ('./index.php');  //重定向到首页
        }
        
        $this -> render('register',array('user_model'=>$user_model,'sex'=>$sex,'xueli'=>$xueli,'hobby'=>$hobby));
    }
    
    function actionCc(){
        echo "cc";
    }
    
    /*
     * 用户退出系统
     */
    function actionLogout(){
        //删除session信息
        //Yii::app()->session->clear();  //删除内存里边sessiion变量信息
        //Yii::app()->session->destroy(); //删除服务器的session文件
        
        //session和cookie一并删除
        Yii::app()->user->logout();
        
        $this->redirect('/');
    }
    
    /*
     * session使用
     */
    function actionS1(){
        echo $this->id."<br />";
        echo $this->action->id."<br />";
        //设置session,通过session组件来设置
        Yii::app()->session['username'] = "zhangsan";
        Yii::app()->session['useraddr'] = "beijing";
        echo "make session success";
    }
    
    function actionS2(){
        //使用session
        echo Yii::app()->session['username'],"<br />";
        echo Yii::app()->session['useraddr'];
        echo "use session success";
    }
    
    function actionS3(){
        //删除一个session
        //unset(Yii::app()->session['useraddr']);
        
        //删除全部session
        Yii::app()->session->clear();  //删除session变量
        Yii::app()->session->destroy(); //删除服务器的session信息
    }
    
    /*
     * cookie在Yii框架使用 
     */
    function actionC1(){
        //设置cookie
        $ck = new CHttpCookie('hobby','篮球,足球');
        $ck -> expire = time()+3600;
        //把$ck对象放入cookie组件里边
        Yii::app()->request->cookies['hobby'] = $ck;
        
        $ck2 = new CHttpCookie('sex','nan');
        $ck2 -> expire = time()+3600;
        //把$ck对象放入cookie组件里边
        Yii::app()->request->cookies['sex'] = $ck2;
        
        echo "cookie make success";
    }
    function actionC2(){
        //访问cookie
        echo Yii::app()->request->cookies['hobby'],"<br />";
        echo Yii::app()->request->cookies['sex'];
    }
    function actionC3(){
        //删除cookie
        unset(Yii::app()->request->cookies['sex']);
    }
    
    function actionLu(){
        //输出路径别名信息/yii就是框架直接可以操作使用的类
        //Yii::app() 是一个实例,是在当前框架里边唯一可以直接使用的实例对象
        //echo Yii::getPathOfAlias('system');  //D:\www\0507\framework
        //echo Yii::getPathOfAlias('system.web');  //D:\www\0507\framework\web
        //echo Yii::getPathOfAlias('application');  //D:\www\0507\shop\protected
        //echo Yii::getPathOfAlias('zii');  //D:\www\0507\framework\zii
        echo Yii::getPathOfAlias('webroot');  //D:/www/0507/shop
        
    }
    
    
    /*
     * 使用Yii::app()调用相关属性、方法
     */
    function actionAp(){
        echo Yii::app()->defaultController,"<br />";
        echo Yii::app()->layout,"<br />";
        echo Yii::app()->name,"<br />";
        echo Yii::app()->charset,"<br />";
        echo Yii::app()->getLayoutPath(),"<br />";
        echo Yii::app()->request->getUrl(),"<br />";
        echo Yii::app()->request->getHostInfo(),"<br />";
    }
    
    /*
     * 计算脚本执行时间
     */
    function actionTime(){
        //查看脚本开始时间
        Yii::beginProfile('mytime');
        for($i=0; $i<=100; $i++){
            if($i%7==0)
                echo "seven<br />";
            else if($i%8==0)
                echo "eight<br />";
            else
                echo $i."<br />";
        }
        Yii::endProfile('mytime');
    }
}

前台user模型:

User.php

<?php
/**
 * 用户模型model
 * 两个基本方法:
 * model
 * tableName
 */
class User extends CActiveRecord{
    //在当前模型增加一个属性password2,因为数据库表里边没有这个属性
    //我们可以在当前类直接设置这个属性使用
    public $password2;
    
    //获得数据模型方法
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }
    
    //定义数据表名字
    public function tableName(){
        return "{{user}}";
    }
    
    //设置标签名字与数据库字段对应
    public function attributeLabels() {
        return array(
            'username'=>'用户名',
            'password'=>'密  码',
            'password2'=>'确认密码',
            'user_sex'=>'性  别',
            'user_qq'=>'qq号码',
            'user_hobby'=>'爱  好',
            'user_xueli'=>'学  历',
            'user_introduce'=>'简  介',
            'user_email'=>'邮  箱',
            'user_tel'=>'手机号码',
        );
    }
    
    /*
     * 实现用户注册表单验证
     * 在模型里边设置一个方法,定义具体表单域验证规则
     */
    public function rules() {
        return array(
            
            array('username','required','message'=>'用户名必填'),
           
            //用户名不能重复(与数据库比较)
            array('username', 'unique', 'message'=>'用户名已经占用'),
            
            array('password','required','message'=>'密码必填'),
            
            //验证确认密码password2  要与密码的信息一致
            array('password2','compare','compareAttribute'=>'password','message'=>'两次密码必须一致'),
            
            //邮箱默认不能为空
            array('user_email','email','allowEmpty'=>false,  'message'=>'邮箱格式不正确'),
            
            //验证qq号码(都是数字组成,5到12位之间,开始为非0信息,使用正则表达式验证)
            array('user_qq','match','pattern'=>'/^[1-9]\d{4,11}$/','message'=>'qq格式不正确'),
            
            //验证手机号码(都是数字,13开始,一共有11位)
            array('user_tel','match','pattern'=>'/^13\d{9}$/','message'=>'手机号码格式不正确'),
            
            //验证学历(信息在2、3、4、5之间则表示有选择,否则没有),1正则;2范围限制
            //范围限制
            array('user_xueli','in','range'=>array(2,3,4,5),'message'=>'学历必须选择'),
                        
            //验证爱好:必选两项以上(自定义方法对爱好进行验证)
            array('user_hobby','check_hobby'),

            //为没有具体验证规则的属性,设置安全的验证规则,否则attributes不给接收信息
            array('user_sex,user_introduce','safe'),
        );
    }
    
    /*
     * 在当前模型里边定义一个方法check_hobby对爱好进行验证
     */
    function check_hobby(){
        //在这个方法里边,我们可以获得模型的相关信息
        //$this -> 属性名;  //调用模型对象的相关属性信息
        //$this 就是我们在控制器controller里边实例化好的模型对象
        
        $len = strlen($this -> user_hobby);
        if($len < 3)
            $this -> addError('user_hobby','爱好必须选择两项或以上');
    }
}
前台登陆视图:

login.php

<style type="text/css">
    div .errorMessage{color:red;}
    label  .required {color:red;}
</style>

            <div class="block box">
            <div class="usBox clearfix">
                <div class="usBox_1 f_l">
                    <div class="logtitle"></div>
                    <?php $form = $this -> beginWidget('CActiveForm'); ?>
                        <table align="left" border="0" cellpadding="3" cellspacing="5" width="100%">
                            <tbody><tr>
                                    <td align="right" width="25%">
                                        <?php echo $form->labelEx($user_login,'username'); ?>
                                    </td>
                                    <td width="75%">
                                        <?php echo $form->textField($user_login,'username',array('size'=>25,'class'=>'inputBg')); ?>
                                        <?php echo $form->error($user_login,'username'); ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td align="right">
                                        <?php echo $form->labelEx($user_login,'password'); ?>
                                    </td>
                                    <td>
                                        <?php echo $form->textField($user_login,'password',array('size'=>15,'class'=>'inputBg')); ?>
                                        <?php echo $form->error($user_login,'password'); ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td align="right">
                                        <?php echo $form->labelEx($user_login, 'verifyCode'); ?>
                                    </td>
                                    <td>
                                        <?php echo $form->textField($user_login, 'verifyCode',array('size'=>15,'class'=>'inputBg','maxlength'=>4)); ?>
                                        <!--显示验证码图片/使用小物件显示验证码-->
                                        <?php $this -> widget('CCaptcha'); ?>
                                        <?php echo $form->error($user_login,'verifyCode'); ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td align="right">
                                        <?php echo $form->checkBox($user_login, 'rememberMe'); ?>
                                    </td>
                                    <td>
                                        <?php echo $form->labelEx($user_login, 'rememberMe'); ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td> </td>
                                    <td align="left">
                                        <input name="submit" value=http://www.mamicode.com/"" class="us_Submit" type="submit" />>前台register.php视图

         <!--放入view具体内容-->
<style type="text/css">
    div .errorMessage{color:red;}
    label  .required {color:red;}
</style>
            <div class="block box">
                <div class="usBox">
                    <div class="usBox_2 clearfix">
                        <div class="logtitle3"></div>
                        <?php $form = $this -> beginWidget('CActiveForm',
                                    array(
                                            'enableClientValidation'=>true,
                                            'clientOptions'=>array(
                                                    'validateOnSubmit'=>true,
                                            ),
                                    )
                                ); 
                        ?>
                        <table cellpadding="5" cellspacing="3" style="text-align:left; width:100%; border:0;">
                                <tbody>
                                    <tr>
                                        <td style="width:13%; text-align: right;">
                                            <?php echo $form->labelEx($user_model, 'username'); ?>
                                        </td>

                                        <td style="width:87%;">
                                             <?php echo $form->textField($user_model,'username',array('class'=>'inputBg','id'=>'User_username')); ?>
                                            <!--表单验证失败显示错误信息-->
                                            <?php echo $form ->error($user_model,'username'); ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                           <?php echo $form->labelEx($user_model, 'password'); ?>
                                        </td>

                                        <td>
                                            <?php echo $form->passwordField($user_model,'password',array('class'=>'inputBg','id'=>'User_password')); ?>
                                            <?php echo $form ->error($user_model,'password'); ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <?php echo $form->label($user_model,'password2') ?>
                                        </td>
                                        <td>
                                             <?php echo $form->passwordField($user_model,'password2',array('class'=>'inputBg','id'=>'User_password2')); ?>
                                            <?php echo $form ->error($user_model,'password2'); ?>
                                        </td>

                                    </tr>
                                    <tr>
                                        <td align="right"><?php echo $form->label($user_model, 'user_email'); ?></td>
                                        <td>
                                            <?php echo $form->textField($user_model,'user_email',array('class'=>'inputBg','id'=>'User_user_email')); ?>
                                            <?php echo $form->error($user_model,'user_email'); ?>
                                        </td>
                                    </tr>
                                    <tr>

                                        <td align="right"><?php echo $form->label($user_model, 'user_qq'); ?></td>
                                        <td>
                                            <?php echo $form->textField($user_model,'user_qq',array('class'=>'inputBg','id'=>'User_user_qq')); ?>
                                            <?php echo $form->error($user_model,'user_qq'); ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right"><?php echo $form->label($user_model, 'user_tel'); ?></td>
                                        <td>
                                            <?php echo $form->textField($user_model,'user_tel',array('class'=>'inputBg','id'=>'User_user_tel','maxlength'=>11)); ?>
                                            <?php echo $form->error($user_model,'user_tel'); ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <!--radioButtonList($model,$attribute,$data,$htmlOptions=array())-->
                                        <td align="right"><?php echo $form->label($user_model, 'user_sex'); ?></td>
                                        <td>
                                            <?php echo $form->radioButtonList($user_model,'user_sex',$sex,array('separator'=>' ')); ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <!--dropDownList($model,$attribute,$data,$htmlOptions=array())-->
                                        <td align="right"><?php echo $form->label($user_model, 'user_xueli'); ?></td>
                                        <td>
                                            <?php echo $form -> dropDownList($user_model,'user_xueli',$xueli); ?>
                                            <?php echo $form->error($user_model,'user_xueli'); ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <!--checkBoxList($model,$attribute,$data,$htmlOptions=array())-->
                                        <td align="right"><?php echo $form->label($user_model, 'user_hobby'); ?></td>
                                        <td>
                                            <?php echo $form -> checkBoxList($user_model,'user_hobby',$hobby,array('separator'=>' ')); ?>
                                            <?php echo $form->error($user_model,'user_hobby'); ?>
                                        </td>
                                    </tr>
                                    <tr>

                                        <!--textArea($model,$attribute,$htmlOptions=array())-->
                                        <td align="right"><?php echo $form->label($user_model, 'user_introduce'); ?></td>
                                        <td>
                                            <?php echo $form -> textArea($user_model,'user_introduce',array('cols'=>50,'rows'=>5)); ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td> </td>

                                        <td align="left">
                                            <input name="Submit" value=http://www.mamicode.com/"" class="us_Submit_reg" type="submit" />>

后台管理员登陆模块


控制器:ManagerController.php

<?php
/**
 * 后台管理员登录控制器
 */
class ManagerController extends Controller{
    /*
     * 实现用户登录
     */
    function actionLogin(){
        $login_model = new LoginForm();
        
        if(isset($_POST['LoginForm'])){
            $login_model->attributes = $_POST['LoginForm'];
            
            //用户名和密码(包括真实性)判断validate,持久化session信息login
            if($login_model->validate() &&  $login_model->login())
                $this->redirect('./index.php?r=houtai/index/index');
        }
        
        //调用模板
        $this ->renderPartial('login',array('login_model'=>$login_model));
    }
    
    /*
     * 管理员退出系统
     */
    function actionLogout(){
        //删除session变量
        Yii::app()->session->clear();
        
        //删除服务器session信息
        Yii::app()->session->destroy();
        
        //页面重定向到登录页面
        $this -> redirect('./index.php?r=houtai/manager/login');
    }
    
}

后台模型:

Manager.php

<?php
/**
 * 后天管理员数据模型manager
 * 基本方法:
 * model()
 * tableName()
 * rules()
 * attributeLabels()
 */
class Manager extends CActiveRecord{
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }
    
    public function tableName() {
        return '{{manager}}';
    }
    
    
}
LoginForm.php

<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class LoginForm extends CFormModel
{
	public $username;
	public $password;
        
	private $_identity;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			// username and password are required
			array('username', 'required','message'=>'用户名必填'),
			array('password', 'required','message'=>'密码必填'),
			// password needs to be authenticated
			//array('password', 'authenticate'),
                    //校验用户名和密码的真实性,通过自定义方法实现校验
                    array('password','authenticate'),
		);
	}
	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new UserIdentity($this->username,$this->password);
			if(!$this->_identity->authenticate())
				$this->addError('password','用户名或密码不存在');
		}
	}
	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
                    'username'=>'用户名',
                    'password'=>'密    码',
		);
	}



	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->username,$this->password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			//$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
		else
			return false;
	}
}

视图login.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta content="MSHTML 6.00.6000.16674" name="GENERATOR" />

        <title>用户登录</title>
<style type="text/css">
.errorMessage {clear:both;}
</style>
        <link href=http://www.mamicode.com/"<?php echo HOUTAI_CSS_URL ?>User_Login.css" type="text/css" rel="stylesheet" />>
好吧,代码有点多,下面就进行分析细节。



  

YII MVC之用户注册和用户登录(一)