Directly Calling a Model Function from a View

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('' => $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') ); ?>