[Yii2] How to create and use Functions on Yii2 Basic and Advanced Templates

A function is an organized and reusable block of code that is used to perform one related action or achieve a specific result.

In creating applications using Yii2, often we need a function to simplify and speed up the creation of the application we are creating.

Well… Now how to make the function we create we can access in view or controller. In this article, we will learn how to create and use functions on Yii2 basic and advanced templates.

The steps of creating and using functions on Yii2 are basic and advanced templates.

  1. 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.
  1. Create a“MyFunction.php”file in the components folder, and write the function as follows:
namespace common\components; //Yii2 Advanced template
namespace app\components;    //Yii2 basic template
 
use yii\base\Component;
 
class MyFunction extends Component
{
    public function hello()
    {
        ......
        return "Hello, World!";
    }
}
}
  1. In Yii2 Advanced, edit the file“common/config/main-local.php”and add the following code:
return [
    'components' => [
        ...............
        'MyFunction'=>[
            'class' =>'common\components\MyFunction'
        ],
        ...........
    ],
];

While on Yii2 Basic, edit the file“config/web.php” and copy the following code

...........
$config = [
    ............
    'components' => [
        ............
        'MyFunction'=>[
            'class' =>'app\components\MyFunction',
        ],
    ],
    ..............
];
...........
  1. 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.

TOP TUTORIALS:  Create a Real-Time Application Dashboard with Yii2, Node.js, MySQL and Chart.js

Good luck…………… Good luck… …

Leave a Comment

Your email address will not be published. Required fields are marked *