ymike 2015-06-28 10:00:39 6000次浏览 3条回复 2 1 0

Yii1.16增加注册模块 Yii2 avanced模板已经默认提供了用户注册模块signup而Yii1.1却没有。无奈目前sae上的yiisae框架是针对yii1.1的。只好自己动手了。(希望yiisae框架尽快推出基于Yii2的版本。) 环境:D:\Programs\APMServ5.2.6\www\htdocs\yii-1\ 项目:testdrive

A. 用yiic生成testdrive项目,在以下网址访问Gii http://127.0.0.1/yii-1/testdrive/index.php?r=gii/default/login 提示需要密码登陆Gii, 密码查看testdrive\protected\config\main.php的modules中的gii部分

'modules'=>array(
    // uncomment the following to enable the Gii tool
    /**/
    'gii'=>array(
        'class'=>'system.gii.GiiModule',
        'password'=>'admin',
        // If removed, Gii defaults to localhost only. Edit carefully to taste.
        'ipFilters'=>array('127.0.0.1','::1'),
    ),
    
),

B. 用Model Generator生成User模型(框架自带testdrive\protected\data\testdrive.db数据库已经建有tbl_user表)

Database Connection *
db
Table Prefix
tbl_
Table Name *
tbl_user
Model Class *
User
Base Class *
CActiveRecord
Model Path *
application.models

生成的protected\models\User.php代码如下:

<?php

/**
 * This is the model class for table "tbl_user".
 *
 * The followings are the available columns in table 'tbl_user':
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $email
 */
class User extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'tbl_user';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('username, password, email', 'required'),
            array('username, password, email', 'length', 'max'=>128),
            // The following rule is used by search().
            //  Please remove those attributes that should not be searched.
            array('id, username, password, email', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'email' => 'Email',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        //  Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('username',$this->username,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('email',$this->email,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}

C. 用Form Generator生成登陆表单signup.php

Model Class *
User
View Name *
signup
View Path *
application.views

protected\views\signup.php代码如下

<?php
/* @var $this UserController */
/* @var $model User */
/* @var $form CActiveForm */
?>

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'user-signup-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // See class documentation of CActiveForm for details on this,
    // you need to use the performAjaxValidation()-method described there.
    'enableAjaxValidation'=>false,
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

    <?php echo $form->errorSummary($model); ?>

    <div class="row">
        <?php echo $form->labelEx($model,'username'); ?>
        <?php echo $form->textField($model,'username'); ?>
        <?php echo $form->error($model,'username'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'password'); ?>
        <?php echo $form->textField($model,'password'); ?>
        <?php echo $form->error($model,'password'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'email'); ?>
        <?php echo $form->textField($model,'email'); ?>
        <?php echo $form->error($model,'email'); ?>
    </div>


    <div class="row buttons">
        <?php echo $model->isNewRecord ? CHtml::submitButton('Submit'):CHtml::submitButton('OK'); ?>
    </div>

<?php $this->endWidget(); ?>

</div><!-- form -->

D. 在protected\controllers\SiteController.php中增加动作actionSignup()

public function actionSignup()
{
    $model=new User;

    // uncomment the following code to enable ajax-based validation
    /*
    if(isset($_POST['ajax']) && $_POST['ajax']==='user-signup-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }
    */

    if(isset($_POST['User']))
    {
        $model->attributes=$_POST['User'];
        
        if($model->validate())
        {
            // form inputs are valid, do something here
            //echo var_dump($model);
            //关键部分:保存用户注册数据到数据库
            if($model->save()){
            echo "Success in singing up!";
            return;
            }
        }
    }
    $this->render('signup',array('model'=>$model));
} 

简便起见,其中保存用户注册数据到数据库后没有生成漂亮的反馈页面,仅仅输出Success in singing up!

E. 在页面布局文件protected\views\layouts\main.php<div id="mainmenu">部分增加一行

<div id="mainmenu">
    <?php $this->widget('zii.widgets.CMenu',array(
        'items'=>array(
            array('label'=>'Home', 'url'=>array('/site/index')),
            array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
            array('label'=>'Contact', 'url'=>array('/site/contact')),
            array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
            array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest),
            array('label'=>'Signup', 'url'=>array('/site/signup'))
            
        ),
    )); ?>
</div><!-- mainmenu -->

其中:array('label'=>'Signup', 'url'=>array('/site/signup')为增加的Signup菜单链接。 这时已经可在页面看到菜单链接并且可以注册。 增加了注册模块的yii-1http://pan.baidu.com/s/1mgIfcxU F. 用注册用户登陆 模板的Login登陆验证没有用到数据库,而是硬编码了两个用户admin和demo,用户名和密码相同。 我们要改为用数据库中的tbl_user表用户信息验证登陆。 将\protected\components\UserIdentity.php中以下标注的“//原来的硬编码验证”部分注释掉,增加“//改用数据库tbl_user中的数据验证用户”。

public function authenticate()
{
    //改用数据库tbl_user中的数据验证用户
    $criteria=new CDbCriteria; 
    $criteria->select='username, password';  // only select the 'title' column 
    $criteria->condition='username=:username'; 
    $criteria->params=array(':username'=>$this->username); 
    $user=User::model()->find($criteria); // $params is not needed
    if(!isset($user))
    $this->errorCode=self::ERROR_USERNAME_INVALID;
    elseif($user->password !== $this->password)
        $this->errorCode=self::ERROR_PASSWORD_INVALID;
    else
        $this->errorCode=self::ERROR_NONE;
    return !$this->errorCode;
    //原来的硬编码验证
    /*$users=array(
    // username => password
    'demo'=>'demo',
    'admin'=>'admin',
    );
    if(!isset($users[$this->username]))
        $this->errorCode=self::ERROR_USERNAME_INVALID;
    elseif($users[$this->username]!==$this->password)
        $this->errorCode=self::ERROR_PASSWORD_INVALID;
    else
        $this->errorCode=self::ERROR_NONE;
    return !$this->errorCode;*/
}

现在你可以注册并用注册用户登陆了。

完工!

觉得很赞
您需要登录后才可以回复。登录 | 立即注册