开发者

CakePhp Routes & Session Variables

开发者 https://www.devze.com 2023-01-05 12:25 出处:网络
Is th开发者_如何学JAVAere an intrinsic reason why I can\'t, in routes.php, route a user based on the contents of a session variable?e.g.

Is th开发者_如何学JAVAere 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!


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.


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().

0

精彩评论

暂无评论...
验证码 换一张
取 消