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

Yii1.1 had a CComponent class that had a CBaseController that was the base class for CController. There was a class /protected/components/Controller.php that included any function in this class for access in any view.

Yii2 no longer has the CComponent class. The Yii2 guide states that "Yii 2.0 splits 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 representation, just like in Yii1.1, using /protected/components/Controller.php?

Several similar topics discuss custom answers , but I would like to know if there is an official way to do this, and not a custom way.

+5
source share
8 answers

Step by step:
1) create the following backend / components directory
2) create the controller "BackendController.php" in the folder "components"

<?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 supported controllers apply to the "BackendController" (for example).

 <?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 an action view page "index.php" (for example)

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

Controller functions are not available in views.

In Yii1, the view attached to the controller, while in Yii2, the view is attached to the View class (this was one of the main changes in Yii2). This separates the controller and view logic, but also makes it difficult to perform global functions, as you noticed.

Yii2 itself also needed global functions. They made "helpers", in fact there are a number of helpers: https://github.com/yiisoft/yii2/tree/master/framework/helpers , each of which provides its own set of global functions for use.

If you haven’t guessed yet, this is the best way to make globals in Yii2. It is also a standard compatible method (PSR-2 or any other) and is considered better encoding than conventional global ones.

So you really have to create your own custom helpers with your global characters, for example:

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

and just indicate that in your view / controller, like any helper:

 use common\components\MyHelpers; MyHelpers::myGlobalToDoSomethingAwesome(); 
+5
source

One option is to create a file (possibly in the component directory) that contains your functions:

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

and then include it in the index.php file:

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

The disadvantage is that this is now beyond the scope of the application. I used this method to create a dd() function (dump and stamp) such as Laravel.

+2
source

You can also create components in YII2

Create a directory and file, the same as in YII1 in the interface or backend, and write the code below in it

interface / 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; } } 

After that, use it in each controller, extending this class as follows:

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

Like, the question has already been answered. But, nevertheless, I would like to answer it in the future.

I am using yii2-app-basic . [ NOTE : The directory structure may differ for yii2-app-advanced .]

My directory structure:

 ->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 [Common controller (see directory structure), which will be extended in all controllers, if necessary.]

 <?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(); } } . . . } 

So, whenever this UsersController.php controller enters the account, the first init() method will be called, and in the init() method, the CommonController checkLoginAccess() method will receive a call automatically. Thus, whenever a member who does not have access to an account, he automatically logs out .

Hope this helps. Any problem / question, feel free to ask.

+1
source

I did not run Yii2, but you should be able to perform similar functions using static functions.

Create a class, say, "MyGlobalFunctions.php" with the following contents

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

in your views you can call this function as

 MyGloabalFunctions::myFunction($args); 
0
source

I am new to Yii and tried this as a solution, for example, the messages displayed in the layout I created a baseController in frontend / components (all controllers extend this BaseController) and always make the necessary material in the init section. and set the data in the view / layout with the parameters $ this-> view-> in the view or layout use the data with the parameters $ this-> I don’t know if this is the best practice. sorry for my bad english i hope this helps

  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; } } } 
0
source

Easy to create component:

 <?php namespace frontend\components; use yii\base\Component; class MyComponent extends Component { public function hello() { return "Hello, World!"; } } 

Register it as a component in your frontend/config/main.php :

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

and finally use it where you need to:

 <?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()?>"> 
0
source

All Articles