开发者

In an MVC approach, should I separate my model functions, or combine then as much as possible?

Should you separate model functions, even if they retrieve the fields of data?

Lets say I have an Articles Model that gets Articles from the database.

I have a function, getUserArticles($id), that gets the users articles. I have a function, getAllArticles($offset, $limit), that gets a list of articles.

Should I leave the two functions separate from one another, or combine them somehow.

The reason I ask is because if I were to alter, 开发者_StackOverflow社区add, or remove a field from the query, I would have to do the change in every function. So if I change my mind and decide I no longer want to show the time_added for every article, I would have to remove it from every function.


It is better to expose two distinct functions to the user of the API but internally you can use the same code for both if you believe that there will be better code reuse that way.

For example: you will define a generic getArticles (used internally only)

   articles getArticles($userId, $offset, $limit) {
      // do searching while handling the different cases if $userId is set or not and the same for the offsets
    }

then you define your exposed functions like this

   articles getUserArticles($id){
     return getArticles($id, -1,-1);
   }

  articles getAllArticles($offset, $limit) {
    return getArticles(-1, $offset, $limit);
  }

NOTE: only do this if you believe there is common code between the two functions. If there is no common code then keep them separate and there is no need for the generic getArticles function which I suggested.

I don't know if the above is valid php code but I think the idea is clear.


Keep them separate. They're logically distinct. If you tried merging them, you'd end up with functions having numerous parameters and complicated internals. Keep it simple, but no simpler. Having these smaller, self-explanatory, methods makes life a whole lot easier on you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜