Heim  >  Artikel  >  Backend-Entwicklung  >  YII2中actions的作用是什么

YII2中actions的作用是什么

PHPz
PHPzOriginal
2016-06-06 20:39:031767Durchsuche

YII2中actions的作用是共用一些功能相同的action,方便调用;当然开发者也可以自已写一些action来进行调用,使用方法即在项目目录下创建common目录,并创建“TestAction.php”文件。

YII2中actions的作用是什么

YII2中actions的作用与使用

我们常在控制器中看到一个actions的方法,这个方法具体的作用是共用一些功能相同的action,方便调用。

当然我们也可以自已写一些action来进行调用。在项目目录下创建common目录,并创建TestAction.php文件。action文件的存放路径可以随意指定。

<?php
 
//注意这里的命名空间,要跟你的目录对应
namespace app\common;
 
use yii\base\Action;
 
//我们需要继承yii\base\Action类
class TestAction extends Action {
 
    //这里面的三个参数的值是通过控制器actions中配置而来的
    public $param1 = null;
    public $param2 = null;
    public $param3 = null;
 
    //实现run方法
    public function run() {
        echo "test run param1: {$this->param1} param2: {$this->param2} param3: {$this->param3}";
    }
}

控制器代码如下:

<?php
 
namespace app\controllers;
 
use YII;
use yii\web\Controller;
 
class IndexController extends Controller
{
    //actions的作用主要是共用功能相同的方法
    public function actions()
    {
        return [
            &#39;test&#39; => [
                &#39;class&#39; => &#39;app\common\TestAction&#39;,
                &#39;param1&#39; => &#39;hello&#39;,
                &#39;param2&#39; => &#39;world&#39;,
                &#39;param3&#39; => &#39;!!!&#39;,
            ],
        ];
    }
}

这样我们在地址栏就可以通过/index/test来访问调用了。

企业微信截图_15923574308073.png

更多相关技术知识,请访问PHP中文网

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn