开发者

Best way to organize applications?.... (MVC design pattern)

When building applications, whats the best way to decide what goes where. How do you know what functions to put in what controllers and models. For example, I'm building an application that is based 开发者_如何学编程highly on location. Users can post different things, that will in turn be shown to other users within a certain distance. Also, each user will have their own profile page that will show everything posted by that user regardless of location.

So I have models like this

class UserModel extends BaseM{
  get_user($uid);
  get_all_users();
  edit_user($new_data);
  delete_user($uid);
  add_user($new_user);
  get_user_articles($uid);
  get_user_reviews($uid);
  get_user_foo($uid);
}

class ArticleModel extends BaseM{
  get_article($aid);
  get_all_articles();
  add_article($new_article);
  delete_article($aid);
}// similar to ReviewModel, and other models

class LocalModel extends BaseM{
  get_local_articles($zip_code, $range);
  get_local_reviews($zip_code, $range);
  get_local_foo($zip_code, $range);
}// holds all location related functions

As you can see, I lumped everything dealing with a user (needs a userID) in the userModel, everything dealing with location (needs a zip-code) in the localModel, and then everything else has its own model.

I was wondering whats the best way to figure out what goes where, is there like a rule of thumb for this kind of stuff?


Well you're 80% there already. You've got your models broken out and that is a big battle. Next design the app that you want. If you end up with a lots of repetitive "elements" on multiple pages, then each element should be a view. Otherwise each page should be a view. Or some combination of the two.

Once you have you pages defined and you know the data flow of the app, all that remains is the controller.

It may be practical in a small app to have a single controller. Or for really complex apps, you may have multiple controllers - no more than one per "page" though.

Just keep in mind - the Model should be view agnostic (you can retool the UI without impacting the model). The views should be blind to where the data comes from or where it's going - everything gets filtered through the controller.

See my previous answer to a similar question here:


I normally use this approach: try to put it somewhere. if after a while you use it, it feels awkward, then it's not in the right place.

In general every model class should have methods that make sense for itself, and eventually return other models. Refrain from putting too much computational intelligence in your models. If there's something that feels strange in either classes, there's probably a third class in between to be discovered.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜