How to write a utility?

Hi Everyone,

I would like to create a class. And would like to write some complex sql queries in methods. And would like to access those methods from view. In other way a utility class.

How to achieve this in YII framework?

Could anyone please suggest me?

You can write a class and place it in components.

Write your methods as statics and call like:

MyClass::complexMethod1($parm1, $param2)

That is a working but very ugly implementation. It would be better to take some time for study the class CActiveRecord and CDbCriteria. A wide part of complex sql queryes can be managed with this class using Yii methods.

Hi Zaccaria,

Thank you for your advice. I am learning slowly. I have a query regarding active record.

In the following code, I believe Post class is using only one table. If I want to use multiple tables, How can I achieve it? And Can I access methods written in Post class through View?

class Post extends CActiveRecord


    public static function model($className=__CLASS__)


        return parent::model($className);



    public function tableName()


        return 'tbl_post';



If you need to use multiple table, you might need learn together, with or join method() in CDBCriteria. Or maybe if the query is too complex just use SQL Query. You can use CDbCommand to execute the query…

All the public function on the POST you can called from View by using this code:


//in the view

echo Post::model()->myMethod($param1, $param2);