HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

How skinny should controllers be, how fat should models be in CakePHP?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
skinnyhowfatcontrollerscakephpshouldmodels

Problem

I know it's a good idea to put all data-related logic in your models in CakePHP, but what would you say about keeping every Model::find() and its particular params in the model? Is this good practice, or just taking things too far?

For example, is this:

PostsController:

function index() {
    $posts = $this->Post->getLatest();
    $this->set(compact('posts'));
}


Post model:

function getLatest() {
    $params = array(
        'conditions' => array('published' => 1),
        'limit' => 5,
        'order' => 'publish_date DESC'
    );
    return $this->find('all', $params);
}


Better than this:

PostsController:

function index() {
    $params = array(
        'conditions' => array('published' => 1),
        'limit' => 5,
        'order' => 'publish_date DESC'
    );
    $posts = $this->Post->find('all', $params);
    $this->set(compact('posts'));
}


Any thoughts? Which is better architecturally?

Solution

It's totally egilable to write shorthand-find functions. This way the controller is not depended of the model's parameters. I tend to go that far, that I don't use any fields directly in my controllers (and thus, not using find in controllers at all).

You could save a variable by defining the array in your find-call aswell ;).

Context

StackExchange Code Review Q#2677, answer score: 4

Revisions (0)

No revisions yet.