Yii2使用$this->context获取当前的Module/Controller/Action

2019-09-03 15:34:19 浏览数 (1)

使用Yii2的时候,在某些场景和环境下需要获得Yii2目前所处于的module(模型)、Controller(控制器)、Action(方法),以及会调用控制器里面已经定义过的一些公共的方法等.对于这些问题Yii2可以在视图层View中使用$this->context这个对象去获得。

使用Yii2的时候,在某些场景和环境下需要获得Yii2目前所处于的module(模型)、Controller(控制器)、Action(方法),以及会调用控制器里面已经定义过的一些公共的方法等.对于这些问题Yii2可以在视图层View中使用$this->context这个对象去获得。

示例:譬如现在(视图层登陆界面)login.php方法下面:

<?php

//得到Yii2的当前的控制器Controller

echo

$this->context->id;

//输出结果:site

//得到Yii2的当前的控制器Action

echo

$this->context->action->id;

//输出结果:login

//得到Yii2的当前的控制器Modules

echo

$this->context->module->id;

//输出结果:basic

(默认简单的Basic)

//得到Yii2的当前的控制器里面的方法

echo

$this->context->actionHello();

//输出结果:Hello

World!!!

//此处的actionHello()

方法为定义在控制器里面的方法(也可以是继承来的)

//所在位置为SiteController里面,用于测试

public

function

actionHello(){

return

'Hello World!!!';

}

?>

在控制器里面

$controllerID = Yii::$app->controller->id;

$actionID = Yii::$app->controller->action->id;

G

M

T

Detect languageAfrikaansAlbanianArabicArmenianAzerbaijaniBasqueBelarusianBengaliBosnianBulgarianCatalanCebuanoChichewaChinese (Simplified)Chinese (Traditional)CroatianCzechDanishDutchEnglishEsperantoEstonianFilipinoFinnishFrenchGalicianGeorgianGermanGreekGujaratiHaitian CreoleHausaHebrewHindiHmongHungarianIcelandicIgboIndonesianIrishItalianJapaneseJavaneseKannadaKazakhKhmerKoreanLaoLatinLatvianLithuanianMacedonianMalagasyMalayMalayalamMalteseMaoriMarathiMongolianMyanmar (Burmese)NepaliNorwegianPersianPolishPortuguesePunjabiRomanianRussianSerbianSesothoSinhalaSlovakSlovenianSomaliSpanishSundaneseSwahiliSwedishTajikTamilTeluguThaiTurkishUkrainianUrduUzbekVietnameseWelshYiddishYorubaZulu

AfrikaansAlbanianArabicArmenianAzerbaijaniBasqueBelarusianBengaliBosnianBulgarianCatalanCebuanoChichewaChinese (Simplified)Chinese (Traditional)CroatianCzechDanishDutchEnglishEsperantoEstonianFilipinoFinnishFrenchGalicianGeorgianGermanGreekGujaratiHaitian CreoleHausaHebrewHindiHmongHungarianIcelandicIgboIndonesianIrishItalianJapaneseJavaneseKannadaKazakhKhmerKoreanLaoLatinLatvianLithuanianMacedonianMalagasyMalayMalayalamMalteseMaoriMarathiMongolianMyanmar (Burmese)NepaliNorwegianPersianPolishPortuguesePunjabiRomanianRussianSerbianSesothoSinhalaSlovakSlovenianSomaliSpanishSundaneseSwahiliSwedishTajikTamilTeluguThaiTurkishUkrainianUrduUzbekVietnameseWelshYiddishYorubaZulu

Text-to-speech function is limited to 200 characters

Options : History : Feedback : Donate

Close

0 人点赞