This is how I created my own model. I need it just to place extra functions that I need but doesn’t belong to other models. I don’t even need attributeNames(). Is it possible to call that model in this way
ExtraFunctions::model()->generateMainMenu()
<?php
class ExtraFunctions extends CModel
{
public function attributeNames()
{}
public function generateMainMenu()
{
}
}
If you want a component/class for project specific functions you can create a simple class with static methods or a CApplicationComponent that you can configure in config/main.php
Create a SiteUtil class in protected/components.
class SiteUtil //maybe extends CComponent
{
public static function generateMainMenu()
{
....
}
//... more helper methods for your application ...
}
//Usage:
SiteUtil::generateMainMenu();
Or, if you want to configure some properties in config/main.php.
class SiteUtil extends CApplicationComponent
{
public $menuOptions=array(... defaultValues here ...);
public function generateMainMenu()
{
//You can use $this->menuOptions or other settings from config/main.php here .....
....
}
//... more helper methods for your application ...
}
//config/main.php
components=>array(
'siteutil'=array(
'class'=>'SiteUtil',
'menuOptions'=>array(.....),
... more settings for public properties ...
)
)
//Usage
Yii::app()->siteutil->generateMainMenu();
//or to override the default settings from config/main.php
$siteUtil=Yii::app()->siteutil;
$siteUtil->menuOptions=array(...);
$siteUtil->generateMainMenu();
I thought of using simple class. but what if I need to preform some sql query and I want to call other models, can I do that without extending my class?
Can you call other models in a controller action? Yes. So to answer your Q. Yes. For MVC, I would put your SQL query in a public function in the model it mainly applies to, or makes sense to you, then call from where ever.
Not sure if this will help, but…
I have an app that has a department table. In the model I have a getListData() function that returns the data for CGridview filtering. I also have a getMenuItems() function that returns an ‘items’ array for a CMenu. It can be used for a dropdown sub menu on the main menu, or as the menuItems for the sidebar CPorlet.
But the upshot is that the Department Model does all the talking to the table.