如何在 Yii2 中编写全局函数并在任何视图中访问它们(不是自定义方式) [英] How to write global functions in Yii2 and access them in any view (not the custom way)
问题描述
Yii1.1 有一个 CComponent 类,它有一个 CBaseControllerCController 的基类.有一个/protected/components/Controller.php 类,它允许在任何视图中访问该类中的任何函数.
Yii1.1 had a CComponent class that had a CBaseController which was the base class for CController. There was a /protected/components/Controller.php class which enabled any function in that class to be accessed in any view.
Yii2 不再拥有 CComponent 类.Yii2 指南 指出Yii 2.0 中断1.1 中的 CComponent 类分为两个类:yii\base\Object 和 yii\base\Component".有谁知道如何在 Yii2 中编写全局函数,并在任何视图中编写它们,就像在 Yii1.1 中使用/protected/components/Controller.php 一样?
Yii2 no longer possess the CComponent class. The Yii2 guide indicates that "Yii 2.0 breaks the CComponent class in 1.1 into two classes: yii\base\Object and yii\base\Component". Does anyone know how to write global functions in Yii2 and them in any view, just like it was in Yii1.1 using /protected/components/Controller.php?
几个类似的主题 讨论自定义答案,但我想知道是否有官方的方式来做到这一点,而不是自定义方式.
A couple of similar topics discuss custom answers, but I would like to know whether there is an official way of doing that, not the custom way.
推荐答案
按照步骤:
1)创建以下目录后端/组件"
2)在components"文件夹中创建BackendController.php"控制器
Follow Step:
1) create following directory "backend/components"
2) create "BackendController.php" controller in "components" folder
<?php
namespace backend\components;
use Yii;
class BackendController extends \yii\web\Controller
{
public function init(){
parent::init();
}
public function Hello(){
return "Hello Yii2";
}
}
3) 所有支持的控制器都扩展到BackendController"(如).
3) all backed controller extend to "BackendController" (like).
<?php
namespace backend\controllers;
use Yii;
use backend\components\BackendController;
class SiteController extends BackendController
{
public function beforeAction($event)
{
return parent::beforeAction($event);
}
public function actionIndex(){
/* You have to able for call hello function to any action and view */
//$this->Hello(); exit;
return $this->render('index');
}
}
4) 创建你的动作视图页面 "index.php" (like)
4) create your action view page "index.php" (like)
<?php
print $this->Hello();
?>
这篇关于如何在 Yii2 中编写全局函数并在任何视图中访问它们(不是自定义方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!