yii注册

完成注册功能, 并实现用户的登录与注销.

在上一节创建好的form页面, 我们可以尝试下点击提交, 发现还是回到了本页面, 却没有将数据放入数据库,怎么讲数据放进数据库呢? 跟我来! 回到UserController里, 找到刚才的actionRegister方法,将它修改如下:

  public function actionRegister() {
                $form = new User;
                if (isset($_POST['User'])) {
                        $form->attributes = $_POST['User'];
                        if ($form->save()) {
                                $this->redirect(array('user/login'));
                        }
                }
 
                $this->pageTitle = '注册';
 
                $this->render('register', array('form' => $form));
        }

$form->attributes =$_POST['User']就成功的把字段里的值都赋给了model, 这时, 我们的model已经有了一些属性,使用$form->save()来将我们的属性保存起来, 这样, 我们就在数据库里创建了一条记录,$form->save()成功后, 页面将跳转到login页面. 赶紧试一下吧.

啊哦, 怎么不行啊, 提示createdTime没有默认值. 这里我们使用一个小技巧可以轻松完成这个功能.打开User.php文件, 添加以下内容:

  protected function beforeSave() {
                if ($this->isNewRecord) {
                        $this->password = md5($this->password);
                        $this->createdTime = time();
                }
                return true;
        }

聪明的你肯定看懂了这里的含义, $this->isNewRecord会判断该记录是新建的,还是修改的, $this->password =md5($this->password)是把密码进行md5加密,$this->createdTime = time()会在新建数据的时候,将当前时间给createdTime字段. 有一点需要注意的地方就是, 结尾一定要数return true来表示该方法执行顺利,否则数据可是不会存入数据库哦.

好了, 重新注册吧, 这时, 我们的数据已经可以顺利存入数据库里, 怎么, 你还不能顺利注册?! 赶紧从头开始看一遍吧.

现在我们来添加login方法.首先在controller里创建login action, 内容如下:

  public function actionLogin() {
                $form = new LoginForm;
                if (isset($_POST['LoginForm'])) {
                        $form->attributes = $_POST['LoginForm'];
                        if ($form->validate())
                                $this->redirect(Yii::app()->user->returnUrl);
                }
 
                $this->pageTitle = '登陆';
 
                $this->render('login', array('user' => $form));
        }

跟我们修改User这个model的方法类似, 我们在protected/models里创建LoginForm模型,作用是实现登录框, 并对登录的用户名和密码进行验证.

class LoginForm extends CFormModel {
        public $username;
        public $password;
        public $rememberMe;
 
        public function rules() {
                return array(
                        array('username, password', 'required'),
                        array('password', 'authenticate'),
                );
        }
 
        public function attributeLabels() {
                return array(
                        'username' => '用户名',
                        'password' => '密码',
                        'rememberMe' => '记住我',
                );
        }
 
        public function authenticate($attribute,$params)
        {
                if(!$this->hasErrors()) {
                        $identity = new UserIdentity($this->username, $this->password);
                        $identity->authenticate();
                        switch($identity->errorCode)
                        {
                                case UserIdentity::ERROR_NONE:
                                        $duration=$this->rememberMe ? 3600*24*30 : 0;
                                        Yii::app()->user->login($identity, $duration);
                                        break;
                                case UserIdentity::ERROR_USERNAME_INVALID:
                                        $this->addError('username','Username is incorrect.');
                                        break;
                                default:
                                        $this->addError('password','Password is incorrect.');
                                        break;
                        }
                }
        }
}

解释2个地方, attributeLabels()方法的作用是, 给字段一个显示在页面上的别名, 比如说, ‘user’=> ‘用户名’,当我们在页面使用的时候,它显示的就是 用户名 而不再是 username了, 大家可以自己试一下. 另一个需要解释的地方就是authenticate方法了,我们给password绑定了一个验证规则就是authenticate方法, 当用户提交了表单后,系统就会使用这个方法来验证password适合能通过验证. 看里面的方法, 使用一个UserIdentity类来验证用户名和密码,这时, 我们创建该类了.

在protected/components目录下创建UserIdentity方法, 什么, 这个类已经有了, 那就别犹豫了,改它吧. 内容如下:

class UserIdentity extends CUserIdentity {
 
        private $_id;
        private $_username;
 
        public function authenticate() {
                $user = User::model()->findByAttributes(array('username' => $this->username));
                if ($user === null) {
                        $this->errorCode = self::ERROR_USERNAME_INVALID;
                } else if ($user->password !== md5($this->password)) {
                        $this->errorCode = self::ERROR_PASSWORD_INVALID;
                } else {
                        $this->_id = $user->id;
                        $this->_username = $user->username;
                        $this->setState('id', $user->id);
                        $this->setState('username', $user->username);
                        $this->errorCode = self::ERROR_NONE;
                }
                return !$this->errorCode;
        }
}

还不理解它吗, 其实很简单, 将用户名为$this->username的记录找出来,并检查它的密码和用户输入的密码是否相同, 如果相同的话, 则设置2个值id和username. 还不理解吗?以后慢慢就懂了.当用户通过验证后,在任何地方使用Yii::app()->user->id就可以得到用户的id了,多方便的.

仿照register, 在protected/views/user目录下创建login.php试图文件, 内容如下:

<?php echo CHtml::beginForm(); ?>
 
<?php echo CHtml::errorSummary($user); ?>
 
<p>
        <?php echo CHtml::activeLabelEx($user, 'username'); ?>
        <?php echo CHtml::activeTextField($user, 'username', array('size' => 20, 'maxlength' => 12)); ?>
</p>
 
<p>
        <?php echo CHtml::activeLabelEx($user, 'password'); ?>
        <?php echo CHtml::activePasswordField($user, 'password', array('size' => 20, 'maxlength' => 12)); ?>
</p>
 
<p>
        <label>&nbsp;</label>
        <?php echo CHtml::submitButton('登陆'); ?>
</p>
 
<?php echo CHtml::endForm(); ?>

回到浏览器里, 访问http://localhost/index.php?r=user/login去登录吧.

我们已经有了注册和登录方法了, 剩下的就是登出了, 人家都说进门容易出门难, 嘿, yii里出去是很容易的,在controller里添加actionLogout()方法, super easy的, 内容如下:

  public function actionLogout()  {
                Yii::app()->user->logout();
                $this->redirect(Yii::app()->user->returnUrl);
        }

怎么样, 够简单吧, 这样, 我们的用户操作模块就算完成了. 下一节开始,我们将如何创建一个admin模块来添加category和article, 我知道这和别的教程顺序不一样,但是我们确实需要程序自己来帮我们添加栏目和文章, 而不是从数据库里添加, 不是吗?


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值