Which Model Should Contain That Method?

Let’s say you have two models – each one modeling a database table – Users & Article. Here there’s nothing to deal with Zend Framwork, but you can think of them as typical models in a ZF application.

What happens if you have to write a getUserArticles method? Where would you put it? Whether this will be the User model or the Article model?Where?

Although technically you can put it in both models my advice is to look at the SQL query. If the FROM clause is containing the user table – than put the method in the User model, but here you’d have something like:

SELECT * FROM Article WHERE user_id = 1

I’d prefer to place it in the Article model!

One thought on “Which Model Should Contain That Method?

  1. Hey there,

    I just wanted to throw in that from my logical understanding it would be better to implement that method on User instead of Article. Why?

    Usually you have your User object which can deliver a set of Articles belonging to it. So you could simply do $user->getArticles(); – the other way round would require you to

    a) use the table class i.e. ArticleS not ArticlE and
    b) passing a parameter to the method – $articles->getUserArticles($userId).

    When working with a somewhat domain-driven model, you should imo really not care which table is being queried when designing your models

Leave a Reply

Your email address will not be published. Required fields are marked *