如何在 Yii2 中编写全局函数并在任何视图中访问它们(不是自定义方式)

How to write global functions in Yii2 and access them in any view (not the custom way)

Yii1.1 有一个 CComponent class,它有一个 CBaseController,它是 CController 的基础 class。有一个 /protected/components/Controller.php class 可以在任何视图中访问 class 中的任何功能。

Yii2 不再拥有 CComponent class。 Yii2 guide 表示 "Yii 2.0 breaks the CComponent class in 1.1 into two classes: yii\base\Object and yii\base\Component"。有谁知道如何在 Yii2 中编写全局函数并在任何视图中编写它们,就像在 Yii1.1 中使用 /protected/components/Controller.php 一样?

几个相似的主题discuss custom answers,但我想知道是否有官方的方法,而不是自定义的方法。

YII2也可以制作组件

在前端或后端创建与YII1相同的目录和文件,并在其中写入以下代码

frontend/components/Controller.php

/**
 * Description of Controller
 *
 * @author mohit
 */

namespace frontend\components;
use Yii;
class Controller extends \yii\web\Controller{
    //put your code here

    public function beforeAction($action) {
        parent::beforeAction($action);
        if(true)
            return true;
        else
            return false;

    }
}

之后通过像这样扩展 class 在每个控制器中使用它-

namespace frontend\controllers;
use Yii;
use frontend\components\Controller;
class SomeController extends Controller
{
    // code
}

按照步骤:
1) 创建以下目录 "backend/components"
2) 在 "components" 文件夹

中创建 "BackendController.php" 控制器
<?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"(喜欢)。

<?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"(喜欢)

<?php
print $this->Hello();
?>

我还没有开始使用 Yii2,但您应该可以使用静态函数实现类似的功能。

创建一个 class,假设 "MyGlobalFunctions.php" 包含以下内容

<?php
class MyGlobalFunctions{
    public static function myFunction($args){
       // logic here
     return someValu here
    }
}

在您看来,您可以将此函数称为

MyGloabalFunctions::myFunction($args);

一个选项是创建一个包含您的函数的文件(可能在您的组件目录中):

function myFunction($parameters)
{
    // Do stuff and return stuff
}

然后将其包含在您的 index.php 文件中:

require_once(__DIR__ . "../components/MyGlobalFunctions.php');

缺点是现在这超出了应用程序的 OOP 范围。我用这种方法创建了一个 dd()(转储和死亡)函数,就像 Laravel 那样。

在视图中无法访问控制器功能。

在 Yii1 中,视图附加到控制器,而在 Yii2 中,视图附加到 View class(这是 Yii2 中的核心变化之一)。正如您所注意到的,这将控制器和视图逻辑分开,但也使全局函数更难。

Yii2 本身也需要全局函数。他们制作了"helpers",实际上有很多帮手:https://github.com/yiisoft/yii2/tree/master/framework/helpers每个人都提供自己的一套全局函数供使用。

如果您还没有猜到,这是在 Yii2 中执行全局变量的最佳方式。它也是符合标准的方式(PSR-2 或其他)并且被认为比普通全局变量更好的编码。

因此,您实际上应该使用全局变量创建自己的自定义助手,例如:

class MyHelpers
{
    public static function myGlobalToDoSomethingAwesome()
    {
        return $awesomeness;
    }
}

并在您的 view/controller 中引用它,就像您对待任何帮助者一样:

use common\components\MyHelpers;
MyHelpers::myGlobalToDoSomethingAwesome();

如题,问题已经回答。但是,我仍然想回答它以备将来使用。

我正在使用 yii2-app-basic。 [注意 : yii2-app-advanced.]

的目录结构可能不同

我的目录结构:

->Root Folder
    ->assets
    ->commands
    .
    .
    ->controllers
        ->SiteController.php
        ->CommonController.php (New common controller created)
    ->mail
    .
    .
    ->modules
        ->users
            ->controllers
                ->UsersController.php
            ->models
                ->Users.php
            ->views
                ->index.php
            ->Users.php
    .
    .
    .

CommonController.php [如果需要,将在所有控制器中扩展的公共控制器(见目录结构)。]

<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;

class CommonController extends Controller
{
    .
    .
    // I used this function for checking login access of user
    public function checkLoginAccess() {
        //Write your own custom code
        // For example
        $loginAccess = "No";
        if($loginAccess == "No") {
            Yii::$app->user->logout();
        }
    }
}

UsersController.php

<?php
namespace app\modules\users\controllers;

use Yii;
.
.
use app\controllers\CommonController;

//Extend CommonController 
class UsersController extends CommonController 
{
  // Inside init() function, use checkLoginAccess() method to be called
  public function init() {
    parent::init();
    if(!Yii::$app->user->isGuest) {
      $this->checkLoginAccess();
    }
  }
    .
    .
    .
}

因此,每当这个 UsersController.php 控制器将进入一个帐户时,第一个 init() 方法将被调用,并且在 init() 方法中CommonController 方法 checkLoginAccess() 将自动调用。因此,每当成员没有登录权限时,he/she 将自动 注销

希望对您有所帮助。任何Problem/Question,随时询问。

我是 Yii 的新手,尝试将其作为布局中显示的示例消息的解决方案 我在 frontend/components 中创建了一个 baseController(所有控制器都扩展了这个 BaseController) 并在 init 部分中执行 always 所需的内容。 并使用 $this->view->params 将数据设置为 view/layout 在视图或布局中使用带有 $this->params 的数据 我不知道这是否是最佳做法.. 抱歉我的英语不好,希望对您有所帮助

 namespace frontend\components;
    use Yii;
    use frontend\models\UserMessages;

    class BaseController extends \yii\web\Controller
    {
        public function init(){
            parent::init();

            // user nachrichten
            if (!Yii::$app->user->isGuest) {
                    $messages = UserMessages::find()
                    ->where(['user_recipient_id' => Yii::$app->user->identity->id])
                    ->orderBy('date_created')
                    ->all();
                    $this->view->params['userMessages'] = $messages;
            }
        }
    }

您可以轻松创建组件:

<?php

namespace frontend\components;

use yii\base\Component;

class MyComponent extends Component
{
    public function hello()
    {
        return "Hello, World!";
    }
}

将其注册为您的 frontend/config/main.php 文件中的一个组件:

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    // Some code goes here
    'components' => [
        // some code here
        'memem' => [
            'class' => 'frontend\components\MyComponent'
        ],
    ],
];

最后在需要的地方使用它:

<?php

/* @var $this \yii\web\View */
/* @var $content string */

use yii\helpers\Html;
use yii\widgets\Breadcrumbs;
?>
<?php $this->beginPage()?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="<?=Yii::$app->charset?>">
  <meta name="usage" value="<?=Yii::$app->memem->hello()?>">

https://www.yiiframework.com/wiki/747/write-use-a-custom-component-in-yii2-0

[components/MyComponent.php]

namespace app\components;


use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;

class MyComponent extends Component
{
 public function welcome()
 {
  echo "Hello..Welcome to MyComponent";
 }

}

[config/web.php]

..
..
'components' => [

         'mycomponent' => [

            'class' => 'app\components\MyComponent',

            ],
           ]
...
...

** 你的控制器 *** [ controllers/TestController.php ]

namespace app\controllers;
use Yii;

class TestController extends \yii\web\Controller
{
    public function actionWelcome()
    {
       Yii::$app->mycomponent->welcome();
    }

}