Detailed explanation of how Yii2 uses $this->context to obtain the current Module, Controller (controller), Action, etc.

黄舟
Release: 2023-03-07 07:28:02
Original
1539 people have browsed it

When using Yii2, in certain scenarios and environments, you need to obtain the module(model) and Controller(controller) that Yii2 is currently in. , Action(method), and will call some public methods that have been defined in the controller. For these problems, Yii2 can use $this-> in the View layerView. Get the object of context. The following is a sample code to explain to you

When using Yii2, in certain scenarios and environments, you need to obtain the module (model), Controller (controller), Action (method) where Yii2 is currently located, and It will call some public methods that have been defined in the controller. For these problems, Yii2 can use the $this->context object in the view layer View to obtain them.

Example: For example, the current (view layer login interface) login.php method is as follows:

<?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
&#39;Hello World!!!&#39;;
}
?>
Copy after login

In the controller

$controllerID
= Yii::$app->controller->id;
$actionID
= Yii::$app->controller->action->id;
Copy after login

The above is the detailed content of Detailed explanation of how Yii2 uses $this->context to obtain the current Module, Controller (controller), Action, etc.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!