How do I use slim framework route get all .. but not include except string
Pergunta
How do I use slim framework route get all .. but not include except string get
/login
$app->get('/.*?', function () use ($uri, $app) {
$app->redirect($uri['public'].'/login');
});
$app->get('/login', function () use ($uri, $app) {
echo 'login view';
});
...
$app->post('/login', function () use ($uri, $app) {
$user_controller = new controller\user_controller();
$user_controller_login = $user_controller->login($uri, $app);
});
Solução
Slim routes are processed in order, so if you define the /login
route before the catch-all, it will work in that order:
$app->get('/login', function() use($app) { ... });
$app->post('/login', ...);
$app->get('/.*', function() use($app) { $app->redirect('/login'); });
Although, I don't usually see 'catch all' style routes. Usually, you'd use URL rewriting to pass to static files not served by routes, and if you're doing this to ensure the user has logged-in to each page, you are better off using Slim Middleware to handle that.
For instance, if you had an authenticate piece of middleware, it could check on each of your routes for a login session/cookie/whatever, and if not found redirect to the login page (also passing the current url so they could be redirected back after login).
$authenticate = function() {
$app = \Slim\Slim::getInstance();
return function() use($app) {
// check for auth here somehow
if (!isset($_SESSION['user'])) {
$app->redirect('/login');
}
};
}
// Use middleware on your defined routes
$app->get('/stuff', $authenticate, function() use($app) { ... });
...