yii框架对独立操作的写法与使用

来源:互联网 发布:淘宝怎么修改差评? 编辑:程序博客网 时间:2024/06/03 19:06

操作有内连操作和独立操作


内联操作直接在控制器中写,醉熏相应规则就好了,很简单的


独立操作就有些意思了,这个设计的思路在我理解是一些方法能让很多控制器来直接使用,达到了代码的复用目的


写法 :

在项目文件中新建 操作类文件

例如



注意继承关系

独立操作通过继承yii\base\Action或它的子类来定义

例如我新建一个hello 的独立操作(当然这没有实际意义,仅仅做说明)

<?php/** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */namespace app\components;use yii\base\Action;/** * This command echoes the first argument that you have entered. * * This command is provided as an example for you to learn how to create console commands. * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */class HelloAction extends Action{    /**     * This command echoes what you have entered as the message.     * @param string $message the message to be echoed.     */    public function run()    {        return 'hello world';    }}


独立操作也完成了,但是怎么使用呢,在控制器中复用actions 方法就可以了,就能把独立操作引入

例如

public function actions(){    return [        'error' => [            'class' => 'yii\web\ErrorAction',        ],        'captcha' => [            'class' => 'yii\captcha\CaptchaAction',            'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,        ],        // 直接引用 hello的操作        'hello'=>[            'class'=>'app\components\HelloAction'    // 注意文件的路径        ]    ];}

怎么使用呢 ? 引入之后当成这个控制器自己的一个方法就好了

例如 :直接在控制器中访问






原创粉丝点击