Yes you're right, you could use the hook with slim.before.router like:
$app->hook('slim.before.router', function() use($app) {
$svc = $app->menuService; // do you use slim ioc?
$menu = $svc->getMenu(); // inject the menu to the app
$app->menu = $menu;
});
You could also use a Middleware
class MyMiddleware extends SlimMiddleware
{
public function call()
{
$conn = new PDO('mysql:host=localhost;dbname=example', 'username', 'password');
$q = $conn->prepare("SELECT id, key, value FROM menu_items");
$menu = $q->fetch();
$this->app->menu = $menu;
$this->next->call();
}
}
How frequently the menu changes? In my opinion if not more than twice per day and those are just a few values to fill a select element, you would be better to have it on a resource (like a json object) and save it directly.
Otherwise i would rather call that query everytime the first query in that session is executed or have it on a in memory database like redis.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…