Russell Seymour
Russell Seymour

Reputation: 1423

Is it possible to have conditional routing in a Silex app?

I am writing a web application that has a front facing website and then an admin console. I would like to be able to have a setting that when set to true means that a holding or maintenance page is displayed on the front end website.

My routes configuration is currently in a yaml file and is read on on each request. But now I want it to be clever enough to know whether it is in maintenance mode or not and if it is to direct all routes to one specific page. Or it could change the routes so that there is only one.

I have thought that this could be done with different files being loaded based on the setting but then means that all routes are static and cannot be retrieved from a database for example. Additionally I have had problems reading from the database during the setup phase of the request. I configured the system to read from the DB as service but this does not appear to be usable at the setup phase, have i got this wrong?

Any pointers gratefully recieved.

Russell

Upvotes: 4

Views: 352

Answers (1)

Fractaliste
Fractaliste

Reputation: 5957

I often use maintenance page with Silex:

At the same place I define $app['debug'] = true; I also define an other variable $app['maintenance'] = true; that I use for various check.

Among them I define a maintenance page as following:

$app->before(function (Request $request, Application $app) {
    if($app['maintenance']){
        $subRequest = Request::create('/maintenance', 'GET');
        return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
    }
});

$app->get('/maintenance', function () use ($app) {
    // Here you can return your maintenance page
    return $app->render('maintenance.twig');
});

Then when I turn on the maintenance variable, every request is redirected to the maintenance route.

As you can see I don't use any yaml configuration file in my app, but the idea is the same with them.

Upvotes: 6

Related Questions