你不应该用垃圾污染你的模型。请始终牢记这些基本的 MVC 原则:
- 您的控制器必须不知道您的模型的实现。
- 不要用与您的应用程序业务模型无关的东西污染您的模型。
始终创建可重用的代码,使您的代码“干燥”(不要重复自己)
顺便问一下,用户名字段的用途是什么?由于表单只对登录的用户可用,用户名已经可以通过 Yii::app()->user 访问。
<?php
// models/ChangePasswordForm.php
class ChangePasswordForm extends CFormModel
{
/**
* @var string
*/
public $currentPassword;
/**
* @var string
*/
public $newPassword;
/**
* @var string
*/
public $newPasswordRepeat;
/**
* Validation rules for this form.
*
* @return array
*/
public function rules()
{
return array(
array('currentPassword, newPassword, newPasswordRepeat', 'required'),
array('currentPassword', 'validateCurrentPassword', 'message'=>'This is not your password.'),
array('newPassword', 'compare', 'compareAttribute'=>'validateNewPassword'),
array('newPassword', 'match', 'pattern'=>'/^[a-z0-9_\-]{5,}/i', 'message'=>'Your password does not meet our password complexity policy.'),
);
}
/**
* I don't know your hashing policy, so I assume it's simple MD5 hashing method.
*
* @return string Hashed password
*/
protected function createPasswordHash($password)
{
return md5($password);
}
/**
* I don't know how you access user's password as well.
*
* @return string
*/
protected function getUserPassword()
{
return Yii::app()->user->password;
}
/**
* Saves the new password.
*/
public function saveNewPassword()
{
$user = UserModel::findByPk(Yii::app()->user->username);
$user->password = $this->createPasswordHash($this->newPassword);
$user->update();
}
/**
* Validates current password.
*
* @return bool Is password valid
*/
public function validateCurrentPassword()
{
return $this->createPasswordHash($this->currentPassword) == $this->getUserPassword();
}
}
示例控制器动作:
public function actionChangePassword()
{
$model=new ChangePasswordForm();
if (isset($_POST['ChangePasswordForm'])) {
$model->setAttributes($_POST['ChangePasswordForm']);
if ($model->validate()) {
$model->save();
// you can redirect here
}
}
$this->render('changePasswordTemplate', array('model'=>$model));
}
示例模板代码:
<?php echo CHtml::errorSummary($model); ?>
<div class="row">
<?php echo CHtml::activeLabel($model,'currentPassword'); ?>
<?php echo CHtml::activePasswordField($model,'currentPassword') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'newPassword'); ?>
<?php echo CHtml::activePasswordField($model,'newPassword') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'newPasswordRepeat'); ?>
<?php echo CHtml::activePasswordField($model,'newPasswordRepeat') ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('Change password'); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div><!-- form -->
模板应该很容易创建。这段代码,经过一些小的调整,可以被复制并粘贴到另一个 Yii 项目中。