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

intumwa picture intumwa · Jul 27, 2015 · Viewed 15.5k times · Source

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 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.

Answer

Bharat Chauhan picture Bharat Chauhan · Jul 27, 2015

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) 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) create your action view page "index.php" (like)

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