AutoLogin

A CakePHP Component that will automatically login the Auth session for a duration if the user requested to (saves data to cookies).

Using the session within models

Monday, November 29th 2010, 12:50am
Topics: CakePHP
Tags: Model, Session
Comments: 7
Permalink - Tinylink

This is something that everyone wants to do, but are afraid it breaks the MVC paradigm. Theoretically, the session should be a model, seeing as how it represents data and manages adds, edits, deletes, etc. Regardless, it's a much easier approach to use the session within the model directly, instead of having to pass it as an argument within each method call. Other developers who have attempted this task either try to import the SessionComponent or to use $_SESSION directly.

If you use the component, then you are using the class outside of its scope (a controller helper). If you use the $_SESSION global, then you don't have the fancy Cake dot notation access (Auth.User.id, etc) as well as its session management and security. But don't worry, Cake comes packaged with this powerful class called CakeSession, which both the session component and helper extend. Merely instantiate this class within your AppModel and you are set.

// Import the class
App::import('Core', 'CakeSession');
 
// Instantiate in constructor
public function __construct($id = false, $table = null, $ds = null) {
	parent::__construct($id, $table, $ds);
 
	$this->Session = new CakeSession();
}
 
// Using it within another model
$user_id = $this->Session->read('Auth.User.id');


Now you have control of the session within the model, bundled with Cake's awesome session management.
Related Entries:

7 Comments

10 / 2 = ?
Allowed: [code] [b] [i] [u]
  • dogmatic69
    dogmatic69.com
    Nov 29th 2010, 05:41
    1 I also think there should be sessions in the models, so do this exact same thing. Just wanted to note that You cant access anything in __construct() or setup() as the session is not started and you get errors when trying that.

    It seems that any of the callbacks or any other methods after setup() are ok.
  • Robust Solution
    Dec 8th 2010, 03:04
    2 It would be better if the cake team provides a getInstance method to singletonize the cake session so we can use it everywhere for both the read mode and the write mode.

    thank you for sharing his code.
  • Robust Solution
    Dec 8th 2010, 03:06
    3 thank you for sharing this code.