MVC: Correct pattern to reference objects from a different model

activerecord, cakephp, cakephp-2.0, design-patterns

Solution

IMHO the function should be in the model that most closely matches the data you're trying to retrieve. Models are the "data layer".

So if you're fetching "popular authors", the function should be in the `Author` model, and so on.

Sometimes a function won't fit any model "cleanly", so you just pick one and continue. There are much more productive design decisions to concern yourself with. :)

BTW, in Cake, related models can be accessed without fetching "other" the model object. So if `Book` is related to `Author`:

//BooksController
$this->Book->Author->get_popular_authors();

//Book Model
$this->Author->get_popular_authors();

ref: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#relationship-types

Problem

I'm using CakePHP2.3 and my app has many associations between models. It's very common that a controller action will involve manipulating data from another model. So I start to write a method in the model class to keep the controllers skinny... But in these situations, I'm never sure which model the method should go in? Here's an example. Say I have two models: Book and Author. Author hasMany Book. In the /books/add view I might want to show a drop-down list of popular authors for the user to select as associated with that book. So I need to write a method in one of the two models. Should I... A. Write a method in the Author model class and call that method from inside the BooksController::add() action... ``` $this->Author->get_popular_authors() ``` B. Write a method in the Book model class that instantiates the other model and uses it's find functions... Ex: ``` //Inside Book::get_popular_authors() $Author = new Author(); $populars = $Author->find('all', $options); return $populars; ``` I think my question is the same as asking "what is the best practice for writing model methods that primarily deal with associations between another model?" How best to decide which model that method should belong to? Thanks in advance. PS: I'm not interested in hearing whether you thinking CakePHP sucks or isn't "true" MVC. This question is about MVC design pattern, not framework(s).

Original source