webman
webman copied to clipboard
How to execute something at webman start
Hi,
Trying to figure out what is the best way to execute a DB query at webman start, without a need to run a query for every single request.
In my case, I am trying to load a complex category structure into a variable for later use. Static configuration in app.php is not sufficient nor do I want to query redis if the structure is cached.
Thanks!
Not sure if it's correct to do it like this (please confirm):
added app\support\bootstrap\Categories::class to bootstrap
created Categories.php in /app/support/bootstrap where I'll use the following:
namespace app\support\bootstrap;
use Webman\Bootstrap; use Workerman\Worker; use support\Db;
class Categories implements Bootstrap {
public static function start($worker)
{
... calling db
saving result as constant
}
}
Yes, it's correct.
A simpler way. Add cache()
function to app/functions.php
function cache($key)
{
static $cache = [];
if (!isset($cache[$key])) {
$cache[$key] = Db::table('xxx')->get();
}
return $cache[$key];
}
In this way, there is no need to add Categories class set bootstrap configuration, and it is more flexible and easy to use.
Great!
And this is set for all users, globally, right?
Yes
Thank you! Appreciate your speedy responses.
Keep it up. Big fan of webman