Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

php - Running a database query before every route runs

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...