I am new to Silex. I want to redirect user to home page if the given route is not found in Silex app. I have done it dirty way placeing at the bootom of my front controler (index.php) those lines of code:
...
/*
* if no route found in controlers above - get curen route
*/
// input "XL-FOLDER-LEARNINGOWY/SILEX/test1/web/index.php" output ['XL-FOLDER-LEARNINGOWY','SILEX','test1','web','index.php']
$file_with_path = explode('/', $_SERVER['PHP_SELF']);
//input ['XL-FOLDER-LEARNINGOWY','SILEX','test1','web,'index.php'] output ['XL-FOLDER-LEARNINGOWY','SILEX','test1','web']
array_pop($file_with_path);
// input ['XL-FOLDER-LEARNINGOWY','SILEX','test1','web'] output "XL-FOLDER-LEARNINGOWY/SILEX/test1/web"
$path = implode('/', $file_with_path);
//input "XL-FOLDER-LEARNINGOWY/SILEX/test1/web/asdasd/asdasdasd/asdasd" output "asdasd/asdasdasd/asdasd"
$route = str_replace($path, '', $_SERVER['REQUEST_URI']);
/*
* redirect to default view - if non route found
*/
$app->get($route, function () use($app) {
return $app['twig']->render('index.twig');
})
->bind('home');
// RUN SILEX APP
$app->run();
Is there is a better way to get curent route that is in the url after base path without all this conversions?.
The easiest way to accomplish this is to simply return a redirect from the error route:
$app->error(function (\Exception $e, $code) use ($app) {
if (404 === $code) {
return $app->redirect($app['url_generator']->generate('home'));
}
// Do something else (handle error 500 etc.)
});