Friday, April 3, 2009

Directly Calling a Model Function from a View

Friday, April 3, 2009

It's always better not to call functions in the model from the view, because it breaks somehow the MVC pattern. However, there might be cases where this approach is needed.

A quick example would be:

class Post extends AppModel {

    var $name = 'Post';

    function user($id, $key = null) {
        if (empty($id)) {
            return null;
        }
        $user = ClassRegistry::init('User')->find('first', array(
            'conditions' => array('User.id' => $id),
            'recursive' => -1
        ));
        if (!$user) {
            return null;
        }
        if ($key == null) {
            return $user;
        } else {
           $user = array_pop($user);
           if (isset($user[$key])) {
               return $user[$key];
           }
           return null;
        }
    }

}

See the above example. The method user() is just a sample method that returns an entire User record for a given ID. In addition, if the second argument is given correctly, only a specific field will be retrieved from a returned row.

Now that we have a model function, we can call it in our view:

<? pr( Post::user(1) ); ?>
<? pr( Post::user(1, 'username') ); ?>

2 comments:

  1. Nice tutorial, but you should add static statement to your function, because you're calling it statically.

    ReplyDelete

Please feel free to post your comment about this article.

 
JamNite ◄Design by Pocket, BlogBulk Blogger Templates