Yii2 Action用法

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);
posted @ 2024-03-30 14:55  胡勇健  阅读(44)  评论(0)    收藏  举报