Model Code - The Correct Way

Hello guys,

I’m trying to figure out the best way of creating a model. I have those simple tables: article, tag, and articlesTags (many-many table).

In article model I have some methods like:

getLatest($criteria)

getPopular($criteria)

In tag model:

getPopular($criteria)

Now I’d like to create a method which would return all the articles for a particular tag so the code would look this I guess:




$tag=Tag::model()->with('articles')->together()->findByPk($tag_id);

return $tag->articles;



Now I really don’t know where to put this code, should it be inside Tag model available as $tag->getArticles() or maybe inside Article model as $article->getAllByTag(Tag & $tag). I’m not sure how to do this correctly. I think the Tag model should not return data from other models, however the Article model should not use any other models as well. I’m really confused here.

I’d love to hear someone’s with rich MVC experience take on this topic.

I don’t think it matters too much, and really depends on how you will be using it, but $tag->getArticles() seems to be preferred since there would be no arguments you’d have to pass to it. I do understand that you don’t want to couple the two together tightly, but sometimes this is the sacrifice for convenience.

Thank you Nick, I’m trying to polish my skills as much as possible.

I don’t see anything wrong with that approach. If a Tag has many articles, then to me it makes sense to have a function that returns all of the articles for that Tag. Doing $article->getAllByTag(Tag & $tag); doesn’t make much sense. What you could do, is have $articles->relatedArticles() method return articles based on the same Tag name of the current $article. This way, you have the best of both.