Which Model Should Contain That Method?

submit to reddit

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!

Related posts:

  1. MVC in Practice: Designing Models
  2. Zend Framework: Cache Database Table Schemes
  3. MySQL Expressions in Zend Framework

You are a GREAT developer? Click here to answer the weekly quiz!

This entry was posted in micro tutorial, web development and tagged , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Which Model Should Contain That Method?

  1. Lukas says:

    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 *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">