Worker mode question #466
-
Heya, I was wondering about worker mode and the way it shares resources: Assuming you have something like a request context (symfony service) you initiallise with infos for the current request, like resources to the specific user and such. Is that a problem in worker mode? Like would it keep that context around for multiple requests? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Essentially, all global/static variables are available from request to request. So, if you store information in static/global variables, your app will probably behave in unexpected ways. However, sometimes you need static variables :). In that case, refactoring the static variable like so works perfectly: class WrongWay {
private static bool $var = false;
public function __construct(RequestObject $request) {
if(!self::$var) {
self::$var = true;
// perform per request initialization
// this will be wrong on the next request because $var will be true!
}
}
}
class BetterWay {
/**
* @var WeakMap<bool>
*/
private static WeakMap $var;
public function __construct(RequestObject $request) {
self::$var ??= new WeakMap();
if((self::$var[$request] ?? false) === true) {
self::$var[$request] = true;
// perform per request initialization
}
}
} It requires a bit of refactoring to store state in a weakmap, but it's the best solution I've come up with so far when migrating legacy code to worker mode. |
Beta Was this translation helpful? Give feedback.
Essentially, all global/static variables are available from request to request. So, if you store information in static/global variables, your app will probably behave in unexpected ways.
However, sometimes you need static variables :). In that case, refactoring the static variable like so works perfectly: