I am trying to create a helper function in Yii 2. To which folder is the PHP file to be added to create a custom helper function in Yii 2 and how do I use it in controllers?
To create some static helpers do the following (these instructions are for the 'Advanced Yii2 Template'. Create a folder under common called components . Inside there create a class called something like: MyHelpers (filename MyHelpers. php ).
What is a Helper Function? A helper function usually comes in handy if you want to add a feature to your Laravel application that can be used at multiple locations within your controllers, views, or model files. These functions can be considered as global functions.
The three main features that components provide to other classes are: Properties. Events. Behaviors.
You can put it in the components folder. Afterwards use the namespace to access it. For example
use app\components\Helper;
and in your code
Helper::something();
Make the helper functions static functions.
To create some static helpers do the following (these instructions are for the 'Advanced Yii2 Template'.
Create a folder under common
called components
. Inside there create a class called something like: MyHelpers
(filename MyHelpers.php
).
<?php
namespace common\components;
// namespace app\components; // For Yii2 Basic (app folder won't actually exist)
class MyHelpers
{
public static function hello($name) {
return "Hello $name";
}
}
Don't forget to include it in your controller etc that you would like to use it in.
use common\components\MyHelpers;
// use app\components\MyHelpers; // For Yii2 Basic (app folder won't actually exist)
And to use it:
MyHelpers::hello("John");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With