Yii2 Action用法
actions方法
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
自定義Action
建立TestAction類 common\action\TestAction.php
<?php
namespace app\common\action;
use yii\base\Action;
class TestAction extends Action{
public $name;
public $age;
public function run(){
echo 'run test action name: '.$this->name.' age: ' .$this->age;
}
}
呼叫
public function actions()
{
return [
'test'=>[
'class'=>'app\common\action\TestAction',
'name'=>'胡勇健',
'age'=>25
]
];
}
訪問
http://www.yii2.com/test/test
errorAction
actions方法新增error
public function actions()
{
return [
'error'=>[
'class'=> 'yii\web\ErrorAction'
]
];
}
新增view
<?php
use yii\helpers\Html;
$this->title = $name;
?>
<div class="site-error">
<h1><?= Html::encode($this->title) ?></h1>
<div class="alert alert-danger">
<?= nl2br(Html::encode($message)) ?>
</div>
<p>
請聯絡管理員.
</p>
</div>
修改配置 config\web.php
'errorHandler' => [
'errorAction' => 'test/error',
],
CaptchaAction 驗證碼
controllers\TestController.php actions方法新增captcha操作
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
生成驗證碼
http://www.yii2.com/test/captcha
驗證方法
$code = 'pedone';
$captcha = new CaptchaValidator();
$captcha->captchaAction = 'test/captcha';
$bool = $captcha->validate($code);
var_dump($bool);