Yii2 Action用法

胡勇健發表於2024-03-30

Yii2 Action用法

actions方法

Yii2 Action用法
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

Yii2 Action用法
<?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;
    }
}

呼叫

Yii2 Action用法
   public function actions()
    {
        return [
            'test'=>[
                'class'=>'app\common\action\TestAction',
                'name'=>'胡勇健',
                'age'=>25
            ]
        ];
    }

訪問

Yii2 Action用法
http://www.yii2.com/test/test

errorAction

actions方法新增error

Yii2 Action用法
 public function actions()
    {
        return [
            'error'=>[
                'class'=> 'yii\web\ErrorAction'
            ]
        ];
    }

新增view

Yii2 Action用法
<?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

Yii2 Action用法
'errorHandler' => [
            'errorAction' => 'test/error',
        ],

CaptchaAction 驗證碼

controllers\TestController.php actions方法新增captcha操作

Yii2 Action用法
public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

生成驗證碼

Yii2 Action用法
http://www.yii2.com/test/captcha

驗證方法

Yii2 Action用法
    $code = 'pedone';
    $captcha = new CaptchaValidator();
    $captcha->captchaAction = 'test/captcha';
    $bool = $captcha->validate($code);
    var_dump($bool);

相關文章