views:

32

answers:

2

Is there an intrinsic reason why I can't, in routes.php, route a user based on the contents of a session variable? e.g.

Router::connect('/dashboard',
    array('controller'=>'users','action'=>'dash',1)
);

works okay, but, replacing the 1 with $_SESSION['userid'] doesn't.

Am I missing something important about session variables here?

Alternative suggestions for rerouting a logged-in user from /dashboard to /controller/view/$userid without using a session variable would be equally appreciated!

+1  A: 

If the dash method is supposed to retrieve and show the user's record, then instead of taking the user ID as an argument, you could retrieve the ID of the currently logged in user from the Auth component.

function dash() {
    $user_id = $this->Auth->user('id');
    // ...
}

If you must, you could load the Session component with App::import().

Mike
I think you're sensible to move the problem inside the function. I haven't used the Auth component much yet (maybe I should investigate it further?) but this could be a quick fix for me: function dash($id) { if(empty($id)) $id = $_SESSION['userid']; ... }I'm still curious as to why session variables and routes.php don't want to mix...
thesunneversets
+1  A: 

The session is not yet started when the routes are parsed. If you're using Cake's session handling, they're started by the Session component, which only loads together with a controller, which happens after routing.

You shouldn't make routes dynamic either, since they're used for reverse routing:

Router::connect('/dashboard', array('controller'=>'users', 'action'=>'dash'));
$html->link('…', array('controller'=>'users', 'action'=>'dash'));
// -> /dashboard

If you'd make this dynamic, this wouldn't work as expected anymore:

Router::connect('/dashboard',
    array('controller'=>'users', 'action'=>'dash', $_SESSION['user']));

$html->link('…', array('controller'=>'users', 'action'=>'dash', 1));
// -> /dashboard

$html->link('…', array('controller'=>'users', 'action'=>'dash', 2));
// -> /users/dash/2

Routes should be a static affair. Routes define your applications URL schema, like a map. It's simply not the place to do any "real work". Everything dynamic is happening in controllers.

deceze