Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which folder to add custom helper functions to in Yii

Tags:

yii2

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?

like image 748
user7282 Avatar asked Dec 01 '14 09:12

user7282


People also ask

How to create helper in Yii2?

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 helper file in laravel?

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.

What are Yii2 components?

The three main features that components provide to other classes are: Properties. Events. Behaviors.


Video Answer


2 Answers

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.

like image 67
Mihai P. Avatar answered Sep 19 '22 14:09

Mihai P.


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");

like image 21
johnsnails Avatar answered Sep 21 '22 14:09

johnsnails