binoy
binoy

Reputation: 1768

Cakephp getting session variable in model without using Auth component

I want to get my session variables in my model. Im not using Auth component. Is there any alternate way ?

Thanks Binoy

Upvotes: 2

Views: 4913

Answers (2)

Chirag Shah
Chirag Shah

Reputation: 1474

Controller File : use Session helper

class AppController extends Controller {
     var $helpers = array('Session');
     function index()
     {
        $this->Session->write('answer', '10'); //$this->Session->write('key','value');
     }
     ....
 }

Now you can access this varibale in your model :

 class AppModel extends Model {

    function validateanswer(){
        CakeSession::read('answer');/*Here u can get value of varibale answer which you set through controller*/
    }
 }

Upvotes: 0

David Yell
David Yell

Reputation: 11855

You would need to use the Session helper to do,

$this->Session->write('key','value');

But as the comment states, you'll be wanting to set a variable in your model and then use the session to write the same value into that variable in the model, rather than accessing the session actually in the model.

Class MyModel Extends AppModel{
  var $username;
  var $password;
}

Then in your controller you could use something along the lines of,

$this->MyModel->username = $this->Session->read('User.id');
$this->MyModel->password = $this->Session->read('User.password');

Upvotes: 6

Related Questions