Moe Sweet
Moe Sweet

Reputation: 3721

Cake PHP: How do I make one variable avaiable across all view and elements

I want to access

across the view files, to switch menus and tabs on and off according to group_id.

How can I achieve this with minimum sacrifice of performance?

Thanks

Upvotes: 0

Views: 471

Answers (3)

Laurent
Laurent

Reputation: 307

What I always do is create a AppHelper and create a method for this. Off course this is similar to deceze's answer but it reduces some code you need to write ;)

function user($key) {
   $user = $this->Session->read('Auth.User');
    if (isset($user[$key])) {
     return $user[$key];
    }
   return false;
 }  

Then you can call the id of the user by $this->Html->user('id');

Upvotes: 2

deceze
deceze

Reputation: 522626

If you use the AuthComponent, it'll store the record of the currently logged-in user in the Session under the key Auth. You can access this anywhere through the session component or helper:

$this->Session->read('Auth.User.name')

Even if you're not using the AuthComponent, the Session is the best place to store information about the current user.

Otherwise and in general, the Configure class is usually a good place to store this kind of global information:

Configure::write('User', array('id' => $id, ...));

Configure::read('User.id');

Upvotes: 4

danielgwood
danielgwood

Reputation: 212

Perhaps you could set the variables you want in your AppController (extended by all sub controllers). You should then be able to access them from all views, though be careful to name them uniquely. CakePHP book - App Controller

Upvotes: 1

Related Questions