开发者

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 goin开发者_开发技巧g 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?


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()


The rule is "skinny controllers, fat models". Put most of your code in the models. The controllers should be simple and route requests


It looks like you are doing it right. If you are concerned about calling Company::model()->findAll() over and over, just do it in the controller once ($companies = Company::model()->findAll()) and pass $companies into the view with render(), just like you do with $model. Then use $companies in the view.

I agree with the "skinny controllers, fat models" paradigm for the most part, but I do one additional thing in my controllers (besides routing): prepare variables for use in the view. This is what you doing when you load the $model from the $_GET string after all. So sometimes I will prepare additional variables, in this case $companies.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜