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.
Follow Step:
1) create following directory "backend/components"
2) create "BackendController.php" controller in "components" folder
3) all backed controller extend to "BackendController" (like).
4) create your action view page "index.php" (like)
I am new to Yii and tried this as solution for example messages that are shown in layout i created a baseController in frontend/components (all controllers extends this BaseController) and do the always needed stuff in the init section. and set the data to the view/layout with $this->view->params in view or layout use the data with $this->params i dont know if this is the best practice .. sorry for my bad english, i hope it helps
One option is to create a file (probably in your components directory) that has your functions in it:
and then include it in your
index.php
file:The disadvantage is that this is now outside the OOP scope of the application. I used this method to create a
dd()
(dump and die) function like Laravel has.As, question is already answered. But, still I would like to answer it for future uses.
I'm using yii2-app-basic. [NOTE : Directory structure may differ for yii2-app-advanced.]
My Directory Structure:
CommonController.php [Common controller(see in directory structure) which will be extended in all controller, if needed.]
UsersController.php
So, Whenever this UsersController.php controller will come into an account, first
init()
method will be called, And ininit()
method CommonController methodcheckLoginAccess()
will get call automatically. So, whenever a member having no login acess, he/she will be automatically logged out.Hope it will help. Any Problem/Question, feel free to ask.
Easily you can create a component:
Register it as a component in your
frontend/config/main.php
file:and finally use it where you need:
You can also make components in YII2
Create a directory and a file same as in YII1 in frontend or backend and write below code in it
frontend/components/Controller.php
After that use it in every controller by extending this class like this-