Simplifying session variable access in Cake PHP

|
In Cake PHP sessions are handled in a special component and helper. This is both a good and bad thing. The good aspect of Cake's abstraction is that the component is able to do a lot of things automatically, such as allowing dot notation access of session array contents as well as giving you the ability to check, read, write, and destroy session variables with logical commands. The bad aspect of this is that it becomes quite tedious to work with session variables as you need to type the whole object function call.

A time saving technique I use is to add the following code to my AppController. You can add this to any controller that works heavily with sessions. The code is:

function beforeFilter() {
// Get session data for appllication use
$this->app = $this->Session->read();
}

function beforeRender() {
// Make app variables available to view
$this->set('app', $this->app);
}

What the above lines do is make all your session variables available to all your controller functions in the array $this->app, so that you can quickly get values by checking $this->app['itemKey']. This is enabled by the line in beforeFilter().

The line in beforeRender() makes the session variables available in your views so that you can do checks on $app['itemKey'].

Please note that these just allow simplified access and not writing. To make sure any new session variable you write is kept you need to use $this->Session->write('key', 'value'), and because the above code basically gives us a cache of our session variables I tend to do all my session variable writing near the end of a function.

3 comments:

Snowrider81 said...

Nice trick to get the Session data into the view,
Thanks!

Himawan Djaya Hendra said...

I wanto to write multi session, like, $this->write->Session('user_name',$usename) and
$this->write->Session('company_id',$companyId), how I can do that? thank you

Himawan Djaya Hendra said...

in cakephp 2xxx, I wanto to write multi session, like, $this->Session->write('user_name',$usename) and
$this->Session->write('company_id',$companyId), how I can do that? thank you

Post a Comment