CakePHP Dynamic Routes Configurations, is it POSSI

2019-07-18 06:21发布

问题:

Im just wondering and curious about how to achieve dynamic routes configuration in cakephp, or as such that I can create two routes like so:

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

without trigerring the error everytime a user go to my site. What I want to do is to set '/' as my default landing page when user is not logged in, but in other way if the user is logged in and Auth session is present, i would like to set the url to '/' but pointing to user's dashboard.

What I thought was importing session in routes.php will work but it was not the way I expected:

App::import('Session', 'Component');
$this->Session = new SessionComponent;

if($this->Session->check('Auth.User')) {
        Router::connect('/', array('controller' => 'users', 'action' => 'dashboard'));
} else {
    Router::connect('/', array('controller' => 'users', 'action' => 'login'));
}

Any help is greatly appreciated, im sure many of us are waiting also for the answer. Thank you very much in advance. And wishing u a Happy Holidays.

回答1:

I would simply switch this on the controller level. Point your / route to UsersController::home, in there do:

function home() {
    if ($this->Auth->user()) {
        $this->dashboard();
    } else {
        $this->login();
    }
}

function dashboard() {
    $this->render('dashboard');
}

function login() {
    $this->render('login');
}