Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...