Need Help Calling Model Method From Another Controller

I have a model A that has logic to connect to an API and then create some new records in the database.

A user enters a website url into a table and the model creates a series of other data using information from the API, most

of this happens in the beforeSave() method. It does call some methods in the model using $this->method().

I now have a need to do something similiar to create missing data for a given url via the API, but from a different controller.

I don’t want to clone the code completely in model B so I thought I would call a new method in Model A from Controller B.

I have found that $this-> refers to the current controller B and put simply it all falls apart really fast.

I was able to change a couple of $this->method() to self::method() but

I am trying to understand what is the best approach in Yii to solve this problem.

Any suggestions or links to information would be appreciated.

Cheers !

Hi AustinGeek,

Well, there’s no “this” controller or “another” controller for a model.

You should not think of the relation between a model and a controller like that. They are not coupled tightly.

For instance, User controller is not coupled with User model. There’s no logical relation between them except that the former is using the latter in it. User controller can use any model it needs. For example, User controller can use Profile model along with User model.

"$this" in User model refers to the instance of User model, not User controller.

"$this" in User controller refers to the instance of User controller, not User model.

As for the current issue, you can make a static function in Model A that performs the job. Then you can call it from beforeSave of Model A, and from everywhere you want using the syntax of ModelName::methodName().

Thanks Softark !

That helps, I am new to the object world. Is my use of self:: correct ?