webman icon indicating copy to clipboard operation
webman copied to clipboard

How to execute something at webman start

Open vilords opened this issue 3 years ago • 5 comments

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!

vilords avatar Jan 12 '22 09:01 vilords

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
}

}

vilords avatar Jan 12 '22 10:01 vilords

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.

walkor avatar Jan 12 '22 11:01 walkor

Great!

And this is set for all users, globally, right?

vilords avatar Jan 12 '22 11:01 vilords

Yes

walkor avatar Jan 12 '22 11:01 walkor

Thank you! Appreciate your speedy responses.

Keep it up. Big fan of webman

vilords avatar Jan 12 '22 11:01 vilords