Running a database query before every route runs

て烟熏妆下的殇ゞ 提交于 2019-12-25 18:59:12

问题


So I am using Slim Framework, idiorm and twig to build an application and have a separate template file for my menu which is included on every page. The menu has a select menu that is generated from a database query and so needs to be included on every route. How can I have this query call on every route without actually declaring it on every route.

Can I use the hook system. I am not sure how to tackle this.

I hope that makes sense.

Thanks


回答1:


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 \Slim\Middleware
{
    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.



来源:https://stackoverflow.com/questions/24879539/running-a-database-query-before-every-route-runs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!