3
\$\begingroup\$

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?

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

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 ;).

\$\endgroup\$
1
  • \$\begingroup\$ Thanks for that. I use the first example I gave (all params in the model) because I feel it scans better and opens more opportunities for model method reuse. I just had a slight nagging doubt that I'm going overboard with it, so I appreciate the feedback. Seeing as nobody else has written otherwise, I reckon it must not be a bad idea. \$\endgroup\$ Commented May 29, 2011 at 19:31
1
\$\begingroup\$

I know this is an old question but i thought i'd share my experience.

I recently had an application where i was sick of defining all the Contain associations every time i wanted to get an a record. So i created an Application::getApplication($id); method that included all my Contains and their conditions.

This worked great, every time i wanted an application i just called this. unfortunately when i moved to production and had to deal with a lot more data this became too slow to use in a lot of places. I had to go back and change all the calls to getApplicaion() to usual finds where i could tweak the Contains parameter to only get what i needed.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.