Search code examples
phpslimidiorm

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


Solution

  • 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.