Global controller object

Hello!

Don’t judge me severely. I’m just a newbie and doing my first steps in understanding YII. Hope somebody could help me.

I want to use some functions from one controller in another controller.

I’ve tried the following code with no success:


class ConfigController extends Controller

{

....

public function actionIndex()

{

   ....

   $some_var = AnotherController::someFunctionFromAnotherController();

}

....

}

Such a code produces the following error:


include(AnotherController.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory

There are two better ways to do this:

  1. Use a base controller (all others inherit it). In your case you can put common functions into Controller.php.

  2. Use behaviors (I recommend to start with this way, so you can enjoy this feature of Yii :) )

Thank you for the reply.

I have read the manual and found a brief newbie-friendly;) description of the behaviors feature at http://www.yiiframework.com/wiki/44/behaviors-events

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.

What I do is the following:

WHen i need to deal with database… i create functions in models that deal with their specific tables

User::model()->specificFunction();

If you are in one controller and wish to call other Model you can do so…

If you wish to have a function that is probably shared with other models, then create a behavior and include it like this in your models:

public function behaviors() {

return array(

 'EJsonBehavior'=&gt;array(


'class'=&gt;'application.behaviors.EJsonBehavior' // it is located at my protected/behaviors folder


  ),


);

}

You see? I say I have the behavior EJsonBehavior and where it is located

How is a behavior class? It could be good to download examples from the extensions so you can see how others have done it but here it goes:




class EJsonBehavior extends CBehavior{

	

	private $owner;

	private $relations;

	

	public function toJSON(){

		$this->owner = $this->getOwner();

		

		if (is_subclass_of($this->owner,'CActiveRecord')){

			

			$attributes = $this->owner->getAttributes();

			

			$this->relations 	= $this->getRelated();

			

			$jsonDataSource = array('jsonDataSource'=>array('attributes'=>$attributes,'relations'=>$this->relations));

			

			return CJSON::encode($jsonDataSource);

		}

		return false;

	}

	private function getRelated()

	{	

		$related = array();

		

		$obj = null;

		

		$md=$this->owner->getMetaData();

		

		foreach($md->relations as $name=>$relation){

			

			$obj = $this->owner->getRelated($name);

			

			$related[$name] = $obj instanceof CActiveRecord ? $obj->getAttributes() : $obj;

		}

	    

	    return $related;

	}

}



It is a class that extends from CBehavior, then, once you declare it in your model class, you just call the function:

$model->toJSON(); // this is using the above example

Hope it helps!

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 ?

if you want to use the result of that function in Data just use Config::model->zfunction(‘any_value’)) no need to write behaviors

---- Also

You dont create a behavior and then call:

$my = new myBehavior();

You attach behaviors to models or you declare them in behaviors() model’s function.


I’m sorry, but I have already tried this way (Config::model()->zfunction(‘any_value’)). See my 1st post (http://www.yiiframework.com/forum/index.php?/topic/13282-global-controller-object/page__view__findpost__p__65117)

PHP Error

Description

include(Config.php) [<a href=‘function.include’>function.include</a>]: failed to open stream: No such file or directory

Moreover the code you sent me

Config::model->zfunction(‘any_value’))

produces the following error

Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /var/www/final/sti/protected/models/Config.php on line 95

I’m completely messed up. Please help me.

It should be :


Config::model()->zfunction('any_value');

But, if you’re using the config class as a global service, then why not wrap it in a CApplicationComponent?

Then you can put it in the application config and access it by this:


Yii::app()->config->set('defaultPagesize', 20);

Yii::app()->config->get('defaultPagesize');

See this:

Extension Config

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.