Vidyadhar Mandke
Vidyadhar Mandke

Reputation: 588

How to declare global functions in Yii

i would like to know how to declare common functions in Yii so that we can call it from any controller, view or model file. for example i would like to declare date function globally.

Upvotes: 1

Views: 3273

Answers (3)

Rohit Suthar
Rohit Suthar

Reputation: 3628

Do like this -

In your components

You need to make a file like - MyClass.php and put it inside components folder. Inside the MyClass.php you can write your functions. Like -

class MyClass extends CApplicationComponent {

 public function get_my_info() {

     //your code here
     //your code here

     return value;
 }
}

In your main.php (config folder) -

'components' => array(
        'myClass' => array(
            'class' => 'ext.components.MyClass',
        ),

Now this function is accessible in whole application (controller, view etc.), Directly call the function get_my_info() any where and it will return your value. Like -

$myInfo = Yii::app()->myClass->get_my_info();

Source - How to create & call custom global function in whole application

Upvotes: 0

briiC
briiC

Reputation: 2134

Somewhere (don't remember) i saw that common functions are in file under config/ directory (but realy anywhere you want). If you name your file common-func.php path to it would be {webroot}/protected/config/common-func.php To make these global functions you need to include this file in {webroot}/index.php.

//user defined functions accessible over all pages
require_once dirname(__FILE__).'/protected/config/common-func.php';

Upvotes: 1

Ankit Chauhan
Ankit Chauhan

Reputation: 404

You can create a component, simply a class in component, and then create static methods. This approach is similar to CHtml, so I think is compliant with the framework style.

Upvotes: 4

Related Questions