Take the 2-minute tour ×

i have the following queries common on few methods of the controllers. so is there a way to organise it ? i will need all the variables in the controller so i cant create a private method and return it.

    // Checks if the User is logged in if yes gathers the ID
    $id = $this->_loggedIN();

    // Find the ItemID from the Item Table
    $itemId = $this->User->Item->itemId('1', $id);

    // Finding the User Data and last Status Message
    $user = $this->User->Item->find('first', array('conditions' => array('Item.id' => $itemId), 'contain' => array('User', 'StatusMessage' => array('limit' => 1, 'order' => 'StatusMessage.created DESC'))));
share|improve this question

2 Answers 2

up vote 1 down vote accepted

How about a function in the AppController? Or even better - AppModel?

share|improve this answer
i can create it in the same controller. but i use $itemId and $user in other things below. u think i need to remove the $user find to a different method ? –  Harsha M V Nov 6 '10 at 16:53
Well, what would you like to organise here, then? –  PawelMysior Nov 6 '10 at 17:03
those three queries repeat 4 times in the same controller. like index() dishes() restaurant() photos() –  Harsha M V Nov 6 '10 at 17:52

Since this seems to pertain to the logged in user, you should do this once and save the data in the session. If you're using the AuthComponent (which you probably should), there already is a generic way to find out whether a user is logged in and what his id is:


All the other data of the user model is accessible in the same way. This is simply stored in the session under the key 'Auth' and is accessible like $this->Session->read('Auth.User.id'). If you want to store even more data about the user in the session (like related items or whatnot), do it once in the login method.

function beforeFilter() {
    $this->Auth->autoRedirect = false;

function login() {
        $item = /* find item */;
        $user = /* find user */;
        $this->Session->write('Auth.Item', $item);
        $this->Session->write('Auth.User', $user);
share|improve this answer

Your Answer


