Add customize functions inside model or inside controller

I want to add a customize function inside model or inside controller. Then what I have to do? Please I am stuck at this point.

The scenario is like that

I have a model imr




class Imr extends CActiveRecord{

    ....

    ....

}



I need to add my custom method related to this Imr model like this




class Imr extends CActiveRecord{

    ....

    ....

    public function imrDetails(){

        ....

        ....

    }

}



but when I am trying to call this function like this




if (isset($_POST['imr_id'])){

   $imr = new Imr;

   $imr->imr_id = $_POST['imr_id'];

			

   $imr->imrDetails();

}



Giving me this error ( Imr and its behaviors do not have a method or closure named "imrDetails" ).

Please help me to solve it.

Please help me :(

What’s your imrDetails method doing?

Also, you may want to read this wiki: Understanding Virtual Attributes and get/set methods

Its returning an array object… I have to refine my search and then the results need to be processed. Then the processed result is returned through an array…

So why don’t you use a getter in your model:


public function getImrDetails() {

    …

    return array(1, 2, 3);

}

Then you can use:


var_dump $imr->imrDetails();

Please take a notice of a typo here. You should use


$imr->imrDetails;

or


$imr->getImrDetails();

to get virtual attribute value.

As for your initial question - your function definition and call looks quite normal to me. Seems like there’s a typo in your code which is not visible to us.

Thanks yugene for spotting the typo.

That was really help full. Thanks everyone. I found one more thing, that I want to share with everyone. Its much easier and flexible as well if we create a component file there and inside it put our code.

But one thing I would like to ask you guys, will it be okay if we add some functions to the models? Will it affect the whole traditional coding structure in Yii?

And thanks again for your replies. :)

Do you mean methods?Model is just a class, with its specific intention, so why not to add a method to this class if this method relevant to the model’s intention?

Thus yes, you can and should add methods to any of your classes if it is a correct place for this definite method: follows MVC structure in our case, follows whole application design, improves the code.

If you mean functions - Yii is OOP framework, so using functions isn’t the best choice from design point of view.