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


yii1.1 had ccomponent class had cbasecontroller base class ccontroller. there /protected/components/controller.php class enabled function in class accessed in view.

yii2 no longer possess ccomponent class. yii2 guide indicates "yii 2.0 breaks ccomponent class in 1.1 2 classes: yii\base\object , yii\base\component". know how write global functions in yii2 , them in view, in yii1.1 using /protected/components/controller.php?

a couple of similar topics discuss custom answers, know whether there official way of doing that, not custom way.

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) backed controller extend "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(){         /* have able call hello function action , view */         //$this->hello(); exit;          return $this->render('index');     } } 

4) create action view page "index.php" (like)

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

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -