Manual
Context switching
What belongs to one request and what belongs to the worker.
Introduction#
Code outside the handler closure in swerve.php runs once, when the worker starts: the application, its configuration, its database connections. Code inside the closure runs once per request, in its own coroutine, and anything it keeps in a local variable or a property it allocated there belongs to that request alone — something shared between requests has to live in whatever survives the closure, such as Swerve::cache() or a service started from swerve.php. See After the response and Write sequential PHP.
Concepts#
- Why code breaks when requests overlap – Under PHP-FPM a request owns its process. A Swerve worker serves many requests, and what they reach through a global is shared.
- Per-request state: Scope and WeakMap – Key state by the request's Scope in a WeakMap: each request sees its own value, and the entry goes when the request ends.
- Service lifetimes: Singleton, Scoped, Ephemeral – A service lives for the worker, for one request, or for one use. Choose by whose data it holds.
- Captive dependencies – A singleton must never hold a scoped object: it keeps the first request's, for every request after it.
- Services that can be shared – A service the whole worker uses is stateless after boot. Request data travels with the request, and per-request variants come from a factory.
Guides#
- Making your application safe for concurrent requests – An adapter running your framework correctly under Swerve doesn't make your own code safe for requests that overlap. The checklist, with a fix for each item.