Skip to content

Commit c1e30cd

Browse files
docs: update translations (#2216)
Translation updates for: extension-workers.md . --------- Co-authored-by: alexandre-daubois <2144837+alexandre-daubois@users.noreply.github.com> Co-authored-by: Alexandre Daubois <alex.daubois@gmail.com>
1 parent d72a9ee commit c1e30cd

File tree

6 files changed

+1031
-0
lines changed

6 files changed

+1031
-0
lines changed

docs/cn/extension-workers.md

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
# 扩展 Worker
2+
3+
扩展 Worker 使您的 [FrankenPHP 扩展](https://frankenphp.dev/docs/extensions/) 能够管理专用的 PHP 线程池,用于执行后台任务、处理异步事件或实现自定义协议。适用于队列系统、事件监听器、调度器等。
4+
5+
## 注册 Worker
6+
7+
### 静态注册
8+
9+
如果您的 worker 不需要用户配置(固定的脚本路径、固定的线程数),您可以直接在 `init()` 函数中注册 worker。
10+
11+
```go
12+
package myextension
13+
14+
import (
15+
"github.com/dunglas/frankenphp"
16+
"github.com/dunglas/frankenphp/caddy"
17+
)
18+
19+
// 与 worker 池通信的全局句柄
20+
var worker frankenphp.Workers
21+
22+
func init() {
23+
// 模块加载时注册 worker。
24+
worker = caddy.RegisterWorkers(
25+
"my-internal-worker", // 唯一名称
26+
"worker.php", // 脚本路径(相对于执行目录或绝对路径)
27+
2, // 固定线程数
28+
// 可选的生命周期钩子
29+
frankenphp.WithWorkerOnServerStartup(func() {
30+
// 全局设置逻辑...
31+
}),
32+
)
33+
}
34+
```
35+
36+
### 在 Caddy 模块中(用户可配置)
37+
38+
如果您计划共享您的扩展(例如通用的队列或事件监听器),您应该将其封装在一个 Caddy 模块中。这允许用户通过 `Caddyfile` 配置脚本路径和线程数。这需要实现 `caddy.Provisioner` 接口并解析 Caddyfile ([查看示例](https://github.com/dunglas/frankenphp-queue/blob/989120d394d66dd6c8e2101cac73dd622fade334/caddy.go))。
39+
40+
### 在纯 Go 应用程序中(嵌入式)
41+
42+
如果您 [在没有 Caddy 的标准 Go 应用程序中嵌入 FrankenPHP](https://pkg.go.dev/github.com/dunglas/frankenphp#example-ServeHTTP),您可以在初始化选项时使用 `frankenphp.WithExtensionWorkers` 注册扩展 worker。
43+
44+
## 与 Worker 交互
45+
46+
一旦 worker 池激活,您就可以向其分派任务。这可以在 [导出到 PHP 的原生函数](https://frankenphp.dev/docs/extensions/#writing-the-extension) 中完成,也可以从任何 Go 逻辑中完成,例如 cron 调度器、事件监听器 (MQTT、Kafka) 或任何其他 goroutine。
47+
48+
### 无头模式:`SendMessage`
49+
50+
使用 `SendMessage` 将原始数据直接传递给您的 worker 脚本。这非常适合队列或简单命令。
51+
52+
#### 示例:一个异步队列扩展
53+
54+
```go
55+
// #include <Zend/zend_types.h>
56+
import "C"
57+
import (
58+
"context"
59+
"unsafe"
60+
"github.com/dunglas/frankenphp"
61+
)
62+
63+
//export_php:function my_queue_push(mixed $data): bool
64+
func my_queue_push(data *C.zval) bool {
65+
// 1. 确保 worker 已准备就绪
66+
if worker == nil {
67+
return false
68+
}
69+
70+
// 2. 分派给后台 worker
71+
_, err := worker.SendMessage(
72+
context.Background(), // 标准 Go 上下文
73+
unsafe.Pointer(data), // 要传递给 worker 的数据
74+
nil, // 可选的 http.ResponseWriter
75+
)
76+
77+
return err == nil
78+
}
79+
```
80+
81+
### HTTP 模拟:`SendRequest`
82+
83+
如果您的扩展需要调用一个期望标准 Web 环境(填充 `$_SERVER``$_GET` 等)的 PHP 脚本,请使用 `SendRequest`
84+
85+
```go
86+
// #include <Zend/zend_types.h>
87+
import "C"
88+
import (
89+
"net/http"
90+
"net/http/httptest"
91+
"unsafe"
92+
"github.com/dunglas/frankenphp"
93+
)
94+
95+
//export_php:function my_worker_http_request(string $path): string
96+
func my_worker_http_request(path *C.zend_string) unsafe.Pointer {
97+
// 1. 准备请求和记录器
98+
url := frankenphp.GoString(unsafe.Pointer(path))
99+
req, _ := http.NewRequest("GET", url, http.NoBody)
100+
rr := httptest.NewRecorder()
101+
102+
// 2. 分派给 worker
103+
if err := worker.SendRequest(rr, req); err != nil {
104+
return nil
105+
}
106+
107+
// 3. 返回捕获的响应
108+
return frankenphp.PHPString(rr.Body.String(), false)
109+
}
110+
```
111+
112+
## Worker 脚本
113+
114+
PHP worker 脚本在一个循环中运行,可以处理原始消息和 HTTP 请求。
115+
116+
```php
117+
<?php
118+
// 在同一个循环中处理原始消息和 HTTP 请求
119+
$handler = function ($payload = null) {
120+
// 情况 1:消息模式
121+
if ($payload !== null) {
122+
return "Received payload: " . $payload;
123+
}
124+
125+
// 情况 2:HTTP 模式(标准 PHP 超全局变量会被填充)
126+
echo "Hello from page: " . $_SERVER['REQUEST_URI'];
127+
};
128+
129+
while (frankenphp_handle_request($handler)) {
130+
gc_collect_cycles();
131+
}
132+
```
133+
134+
## 生命周期钩子
135+
136+
FrankenPHP 提供了钩子,用于在生命周期的特定点执行 Go 代码。
137+
138+
| 钩子类型 | 选项名称 | 签名 | 上下文与用例 |
139+
| :------- | :--------------------------- | :----------------------- | :--------------------------------------------------- |
140+
| **服务器** | `WithWorkerOnServerStartup` | `func()` | 全局设置。**只运行一次**。示例:连接到 NATS/Redis。 |
141+
| **服务器** | `WithWorkerOnServerShutdown` | `func()` | 全局清理。**只运行一次**。示例:关闭共享连接。 |
142+
| **线程** | `WithWorkerOnReady` | `func(threadID int)` | 每线程设置。在线程启动时调用。接收线程 ID。 |
143+
| **线程** | `WithWorkerOnShutdown` | `func(threadID int)` | 每线程清理。接收线程 ID。 |
144+
145+
### 示例
146+
147+
```go
148+
package myextension
149+
150+
import (
151+
"fmt"
152+
"github.com/dunglas/frankenphp"
153+
frankenphpCaddy "github.com/dunglas/frankenphp/caddy"
154+
)
155+
156+
func init() {
157+
workerHandle = frankenphpCaddy.RegisterWorkers(
158+
"my-worker", "worker.php", 2,
159+
160+
// 服务器启动(全局)
161+
frankenphp.WithWorkerOnServerStartup(func() {
162+
fmt.Println("扩展:服务器正在启动...")
163+
}),
164+
165+
// 线程就绪(每线程)
166+
// 注意:此函数接受一个表示线程 ID 的整数
167+
frankenphp.WithWorkerOnReady(func(id int) {
168+
fmt.Printf("扩展:Worker 线程 #%d 已就绪。\n", id)
169+
}),
170+
)
171+
}
172+
```

docs/fr/extension-workers.md

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
# Workers d'extension
2+
3+
Les Workers d'extension permettent à votre [extension FrankenPHP](https://frankenphp.dev/docs/extensions/) de gérer un pool dédié de threads PHP pour exécuter des tâches en arrière-plan, gérer des événements asynchrones ou implémenter des protocoles personnalisés. Cela se révèle utile pour les systèmes de files d'attente, les event listeners, les planificateurs, etc.
4+
5+
## Enregistrement du Worker
6+
7+
### Enregistrement statique
8+
9+
Si vous n'avez pas besoin de rendre le worker configurable par l'utilisateur (chemin de script fixe, nombre de threads fixe), vous pouvez simplement enregistrer le worker dans la fonction `init()`.
10+
11+
```go
12+
package myextension
13+
14+
import (
15+
"github.com/dunglas/frankenphp"
16+
"github.com/dunglas/frankenphp/caddy"
17+
)
18+
19+
// Handle global pour communiquer avec le pool de workers
20+
var worker frankenphp.Workers
21+
22+
func init() {
23+
// Enregistre le worker lorsque le module est chargé.
24+
worker = caddy.RegisterWorkers(
25+
"my-internal-worker", // Nom unique
26+
"worker.php", // Chemin du script (relatif à l'exécution ou absolu)
27+
2, // Nombre de threads fixe
28+
// Hooks de cycle de vie optionnels
29+
frankenphp.WithWorkerOnServerStartup(func() {
30+
// Logique de configuration globale...
31+
}),
32+
)
33+
}
34+
```
35+
36+
### Dans un module Caddy (configurable par l'utilisateur)
37+
38+
Si vous prévoyez de partager votre extension (comme une file d'attente générique ou un écouteur d'événements), vous devriez l'envelopper dans un module Caddy. Cela permet aux utilisateurs de configurer le chemin du script et le nombre de threads via leur `Caddyfile`. Cela nécessite d'implémenter l'interface `caddy.Provisioner` et de parser le Caddyfile ([voir un exemple](https://github.com/dunglas/frankenphp-queue/blob/989120d394d66dd6c8e2101cac73dd622fade334/caddy.go)).
39+
40+
### Dans une application Go pure (intégration)
41+
42+
Si vous [intégrez FrankenPHP dans une application Go standard sans Caddy](https://pkg.go.dev/github.com/dunglas/frankenphp#example-ServeHTTP), vous pouvez enregistrer des workers d'extension en utilisant `frankenphp.WithExtensionWorkers` lors de l'initialisation des options.
43+
44+
## Interaction avec les Workers
45+
46+
Une fois le pool de workers actif, vous pouvez lui envoyer des tâches. Cela peut être fait à l'intérieur de [fonctions natives exportées vers PHP](https://frankenphp.dev/docs/extensions/#writing-the-extension), ou à partir de toute logique Go telle qu'un planificateur cron, un écouteur d'événements (MQTT, Kafka), ou toute autre goroutine.
47+
48+
### Mode sans tête : `SendMessage`
49+
50+
Utilisez `SendMessage` pour passer des données brutes directement à votre script worker. C'est idéal pour les files d'attente ou les commandes simples.
51+
52+
#### Exemple : Une extension de file d'attente asynchrone
53+
54+
```go
55+
// #include <Zend/zend_types.h>
56+
import "C"
57+
import (
58+
"context"
59+
"unsafe"
60+
"github.com/dunglas/frankenphp"
61+
)
62+
63+
//export_php:function my_queue_push(mixed $data): bool
64+
func my_queue_push(data *C.zval) bool {
65+
// 1. S'assurer que le worker est prêt
66+
if worker == nil {
67+
return false
68+
}
69+
70+
// 2. Envoyer au worker en arrière-plan
71+
_, err := worker.SendMessage(
72+
context.Background(), // Contexte Go standard
73+
unsafe.Pointer(data), // Données à passer au worker
74+
nil, // http.ResponseWriter optionnel
75+
)
76+
77+
return err == nil
78+
}
79+
```
80+
81+
### Émulation HTTP : `SendRequest`
82+
83+
Utilisez `SendRequest` si votre extension doit invoquer un script PHP qui s'attend à un environnement web standard (remplir `$_SERVER`, `$_GET`, etc.).
84+
85+
```go
86+
// #include <Zend/zend_types.h>
87+
import "C"
88+
import (
89+
"net/http"
90+
"net/http/httptest"
91+
"unsafe"
92+
"github.com/dunglas/frankenphp"
93+
)
94+
95+
//export_php:function my_worker_http_request(string $path): string
96+
func my_worker_http_request(path *C.zend_string) unsafe.Pointer {
97+
// 1. Préparer la requête et l'enregistreur
98+
url := frankenphp.GoString(unsafe.Pointer(path))
99+
req, _ := http.NewRequest("GET", url, http.NoBody)
100+
rr := httptest.NewRecorder()
101+
102+
// 2. Envoyer au worker
103+
if err := worker.SendRequest(rr, req); err != nil {
104+
return nil
105+
}
106+
107+
// 3. Retourner la réponse capturée
108+
return frankenphp.PHPString(rr.Body.String(), false)
109+
}
110+
```
111+
112+
## Script Worker
113+
114+
Le script worker PHP s'exécute dans une boucle et peut gérer à la fois les messages bruts et les requêtes HTTP.
115+
116+
```php
117+
<?php
118+
// Gérer à la fois les messages bruts et les requêtes HTTP dans la même boucle
119+
$handler = function ($payload = null) {
120+
// Cas 1 : Mode Message
121+
if ($payload !== null) {
122+
return "Received payload: " . $payload;
123+
}
124+
125+
// Cas 2 : Mode HTTP (les superglobales PHP standards sont peuplées)
126+
echo "Hello from page: " . $_SERVER['REQUEST_URI'];
127+
};
128+
129+
while (frankenphp_handle_request($handler)) {
130+
gc_collect_cycles();
131+
}
132+
```
133+
134+
## Hooks de Cycle de Vie
135+
136+
FrankenPHP fournit des hooks pour exécuter du code Go à des points spécifiques du cycle de vie.
137+
138+
| Type de Hook | Nom de l'Option | Signature | Contexte et Cas d'Utilisation |
139+
| :--------- | :--------------------------- | :------------------- | :--------------------------------------------------------------------- |
140+
| **Serveur** | `WithWorkerOnServerStartup` | `func()` | Configuration globale. Exécuté **Une fois**. Exemple : Connexion à NATS/Redis. |
141+
| **Serveur** | `WithWorkerOnServerShutdown` | `func()` | Nettoyage global. Exécuté **Une fois**. Exemple : Fermeture des connexions partagées. |
142+
| **Thread** | `WithWorkerOnReady` | `func(threadID int)` | Configuration par thread. Appelé lorsqu'un thread démarre. Reçoit l'ID du Thread. |
143+
| **Thread** | `WithWorkerOnShutdown` | `func(threadID int)` | Nettoyage par thread. Reçoit l'ID du Thread. |
144+
145+
### Exemple
146+
147+
```go
148+
package myextension
149+
150+
import (
151+
"fmt"
152+
"github.com/dunglas/frankenphp"
153+
frankenphpCaddy "github.com/dunglas/frankenphp/caddy"
154+
)
155+
156+
func init() {
157+
workerHandle = frankenphpCaddy.RegisterWorkers(
158+
"my-worker", "worker.php", 2,
159+
160+
// Démarrage du Serveur (Global)
161+
frankenphp.WithWorkerOnServerStartup(func() {
162+
fmt.Println("Extension : Démarrage du serveur...")
163+
}),
164+
165+
// Thread Prêt (Par Thread)
166+
// Note : La fonction accepte un entier représentant l'ID du Thread
167+
frankenphp.WithWorkerOnReady(func(id int) {
168+
fmt.Printf("Extension : Le thread worker #%d est prêt.\n", id)
169+
}),
170+
)
171+
}
172+
```

0 commit comments

Comments
 (0)