Skip to content

Commit 1471aa1

Browse files
committed
docs: improver worker docs, and add internals docs
1 parent efbbfa3 commit 1471aa1

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

docs/worker.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,3 +168,38 @@ $handler = static function () use ($workerServer) {
168168

169169
// ...
170170
```
171+
172+
Most superglobals (`$_GET`, `$_POST`, `$_COOKIE`, `$_FILES`, `$_SERVER`, `$_REQUEST`) are automatically reset between requests.
173+
However, **`$_ENV` is not reset between requests** for performance reasons.
174+
This means that any modifications made to `$_ENV` during a request will persist and be visible to subsequent requests handled by the same worker thread.
175+
Avoid storing request-specific or sensitive data in `$_ENV`.
176+
177+
## State Persistence
178+
179+
Because worker mode keeps the PHP process alive between requests, the following state persists across requests:
180+
181+
- **Static variables**: Variables declared with `static` inside functions or methods retain their values between requests.
182+
- **Class static properties**: Static properties on classes persist between requests.
183+
- **Global variables**: Variables in the global scope of the worker script persist between requests.
184+
- **In-memory caches**: Any data stored in memory (arrays, objects) outside the request handler persists.
185+
186+
This is by design and is what makes worker mode fast. However, it requires attention to avoid unintended side effects:
187+
188+
```php
189+
<?php
190+
function getCounter(): int {
191+
static $count = 0;
192+
return ++$count; // Increments across requests!
193+
}
194+
195+
$handler = static function () {
196+
echo getCounter(); // 1, 2, 3, ... for each request on this thread
197+
};
198+
199+
for ($nbRequests = 0; ; ++$nbRequests) {
200+
if (!\frankenphp_handle_request($handler)) break;
201+
}
202+
```
203+
204+
When writing worker scripts, make sure to reset any request-specific state at the beginning of each request handler.
205+
Frameworks like [Symfony](symfony.md) and [Laravel Octane](laravel.md) handle this automatically.

0 commit comments

Comments
 (0)