大家都知道yii2是一个组件化的php框架,框架中集成了各种各样的组件,供PHPER来使用,有时某些组件不太符合自己的需求,但是可以自定义组件,或者在原有组件基础上扩展组件。
话不多说,本例以扩展yii2的验证码组件为例,来解决验证码不随页面刷新而刷新的问题。
一、自己的的组件目录下新建 CustomCaptcha.php (文件名可自定义) ,其中文件内容如下:
namespace app\components;
use Yii;
use yii\helpers\Url;
use yii\web\Response;
use yii\captcha\CaptchaAction;
class CustomCaptcha extends CaptchaAction{
/**
* 重写 Runs the action.
*/
public function run(){
if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) {
// AJAX request for regenerating code
$code = $this->getVerifyCode(true);
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'hash1' => $this->generateValidationHash($code),
'hash2' => $this->generateValidationHash(strtolower($code)),
// we add a random 'v' parameter so that FireFox can refresh the image
// when src attribute of image tag is changed
'url' => Url::to([$this->id, 'v' => uniqid()]),
];
} else {
$this->setHttpHeaders();
Yii::$app->response->format = Response::FORMAT_RAW;
//return $this->renderImage($this->getVerifyCode()); //以前的代码
return $this->renderImage($this->getVerifyCode(true)); //新增加的代码
}
}
}
二、在你的控制器文件中,添加如下代码:
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
//'class' => 'yii\captcha\CaptchaAction', //以前的代码
'class' => 'app\components\CustomCaptcha', //新增加的代码
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'maxLength' => 5,
'minLength' => 5
],
];
}
三、再次刷新带有验证码的页面,观察是否随着页面刷新而刷新。