A function is an organized and reusable block of code that is used to perform one related action or achieve a specific result.
Well… Now how to make the function we create we can access in view or controller.
The steps of creating and using functions on Yii2 are basic and advanced templates.
- Create a folder with the name “components”. For Yii2 basic create the folder in root and on Yii2 advanced create that folder in the “common” folder.
- Create a“MyFunction.php”file in the components folder, and write the function as follows:
namespace commoncomponents; //Yii2 Advanced template namespace appcomponents; //Yii2 basic template use yiibaseComponent; class MyFunction extends Component { public function hello() { ...... return "Hello, World!"; } } }
- In Yii2 Advanced, edit the file“common/config/main-local.php”and add the following code:
return [ 'components' => [ ............... 'MyFunction'=>[ 'class' =>'commoncomponentsMyFunction' ], ........... ], ];
While on Yii2 Basic, edit the file“config/web.php” and copy the following code
........... $config = [ ............ 'components' => [ ............ 'MyFunction'=>[ 'class' =>'appcomponentsMyFunction', ], ], .............. ]; ...........
- To use the function that you have created is enough to call it by
Yii::$app->MyFunction->hello())
You can call the function on both Controller and View.
Good luck…………… Good luck… …