[Yii2] How to create and use Functions on Yii2

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.
yii2 function 01
  1. 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!";
    }
}
}
  1. 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',
        ],
    ],
    ..............
];
...........
  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.

Good luck…………… Good luck… …

RELATED ARTICLES

Latest Articles