But what about the case the method I want to use in another controller is supposed to work with model (search for a specific value in the database: Another::model()->find(…)??
How can I use this method in my new class (class MyBehavior extends CBehavior)? Could you please send me a little snippet of code to show the case? I would appreciate it greatly!
Thank you very much. But there are still some unclear points.
What I’m doing now:
I have two controllers.
ConfigController.php
DataController.php
and correspondent models:
Config.php
Data.php
There is a function in the Config.php that performs some actions.
public function zfunction($var) {
$result = $this->find('name=:name',array(':name'=>$var)); // let's say, this function looks for a record where name = $var
return $result;
}
This function is called from ConfigController.php (Config::model()->zfunction(‘any_value’))
I want to use the result of this function in Data.php
As advised above I’m adding the code into models/Config.php and models/Data.php:
public function behaviors() {
return array(
'MyBehavior'=>array(
'class'=>'application.behaviors.MyBehavior' // it is located at my protected/behaviors folder
),
);
}
and a function into Data.php:
public function some_function() {
$my = new MyBehavior();
$result = $my->zfunction('some_value');
......
}
But what is my next step? What should I put into behavior/MyBehavior.php?
class MyBehavior extends CBehavior{
public function zfunction($var){
//die('test'); // this code is reached i.e. code above is correct but what should be in this function?
return <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/huh.gif' class='bbc_emoticon' alt='???' />
}
}
upd:
another question: how can I also use this function in views/layouts/main.php ?
You can implement the behaviors feature or you can use good old fashioned inheritance.
Using inheritance, I created a BaseController class and gave it the functionality that other controllers needed to share. All my controllers inherit from that controller.
In my case I had to do a require_once("BaseController.php") at the top of each controller class. Perhaps there is a better way to do that.