Silex permet d'éxécuter du code avant ou après la fonction de la route appelée
On les appelle middlewares
$app->before(function() use ($app)
{
// Code exécuté avant la route
});
$app->after(function() use ($app)
{
// Code exécuté après la route
});
$app->finish(function() use ($app)
{
// Code exécuté après que la page ait été renvoyée au visiteur
});
Il est possible d'associer des middleswares uniquement à certaines routes
$before = function() use ($app)
{
// ...
};
$app->get('/', function()
{
// ...
})
->before($before);
$app->before() use ($app) {
$app['twig']->addGlobal('title','Hetic Pokedex');
});
<body>
<head>
<title>{{title}}</title>
</head>
echo '';
print_r($_SERVER);
echo '
';
exit;
// ...
// Config
$config = array();
switch($_SERVER['HTTP_HOST'])
{
case 'localhost':
$config['debug'] = true;
$config['db_host'] = 'localhost';
$config['db_name'] = 'hetic-p2018-blog-G1';
$config['db_user'] = 'root';
$config['db_pass'] = 'root';
break;
case 'preprod.monsite.com':
$config['debug'] = true;
$config['db_host'] = '';
$config['db_name'] = '';
$config['db_user'] = '';
$config['db_pass'] = '';
break;
case 'monsite.com':
$config['debug'] = false;
$config['db_host'] = '';
$config['db_name'] = '';
$config['db_user'] = '';
$config['db_pass'] = '';
break;
}
// App
$app = new Silex\Application();
$app['config'] = $config;
$app['debug'] = $app['config']['debug'];
// ...
// ...
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => array (
'driver' => 'pdo_mysql',
'host' => $app['config']['db_host'],
'dbname' => $app['config']['db_name'],
'user' => $app['config']['db_user'],
'password' => $app['config']['db_pass'],
'charset' => 'utf8'
),
));
// ...
Dans index.php
// Error
$app->error(function (\Exception $e, $code) use ($app)
{
$data = array(
'title' => 'Error'
);
return $app['twig']->render('pages/error.twig',$data);
});
Dans une nouvelle vue views/pages/error.twig
{{include('partials/header.twig')}}
Page not found
{{include('partials/footer.twig')}}
// Error
$app->error(function (\Exception $e, $code) use ($app)
{
if($app['debug'])
return;
$data = array(
'title' => 'Error'
);
return $app['twig']->render('error.twig',$data);
});
Dans la route home
$app->get('/', function() use ($app,$articles_model) {
$query = $app['db']->query('SELECT * FROM articles');
$articles = $query->fetchAll();
$data = array(
'title' => 'Home',
'articles' => $articles
);
return $app['twig']->render('page.twig',$data);
})
->bind('home');
$app->get('/test', function() use ($app)
{
$url = $app['url_generator']->generate('pokemon',array('id'=>88));
return $app->redirect($url);
});