Search code examples
phpmodel-view-controlleryiimodels

Yii - The line between Models and Controllers - What methods where? MVC Principles


in Yii, lets say I have an Employee table, and a Company table. A Company hasMany Emlpoyee. An Emloyee belongsTo a Company.

In the form for creating a new Employee, I want to pull a list of all the companies that exist and put them in a drop down. I know I can do this:

$form->dropDownList($model, 'company_id', CHtml::listData(Company::model()->findAll(),'id', 'company')

But I'm going to have a lot of these in each form (pertaining to different models), so I'm thinking of putting this sort of functionality in their own methods -- something like $model->getCompanies().

My question is, where is the best place for this method?

Should it go in the Company model? The from the view, I would access it as:

Company::model()->getCompanies()

Should it go in the Station model? This doesn't really make sense to me since it seems like something I would 'ask' Company, but then my view code would be:

$model->getCompanies()

Or lastly, should I put the getCompanies() method in the Company model, and then call that method from the actionCreate() of the StationsController, and send the result to the render() for the view?

Whats the most logical way from an MVC perspective?


Solution

  • Logically all of that goes in the Company active record. Fetching a list of companies is working with data in the Company table. Since the purpose of an active record is to group all functionality related to that specific table, the functionality should go in there.

    Btw, if you just want a list of companies you don't have to create a new function, just do a Company::model()->findAll()