diff --git a/caddy/admin_test.go b/caddy/admin_test.go index 4c84c2348b..1318a727fa 100644 --- a/caddy/admin_test.go +++ b/caddy/admin_test.go @@ -225,8 +225,6 @@ func TestAddModuleWorkerViaAdminApi(t *testing.T) { skip_install_trust admin localhost:2999 http_port `+testPort+` - - frankenphp } localhost:`+testPort+` { @@ -252,8 +250,6 @@ func TestAddModuleWorkerViaAdminApi(t *testing.T) { skip_install_trust admin localhost:2999 http_port ` + testPort + ` - - frankenphp } localhost:` + testPort + ` { diff --git a/caddy/caddy.go b/caddy/caddy.go index cd81fd4f0a..24273126a3 100644 --- a/caddy/caddy.go +++ b/caddy/caddy.go @@ -33,10 +33,6 @@ const ( var iniError = errors.New("'php_ini' must be in the format: php_ini \"\" \"\"") -// FrankenPHPModule instances register their workers, and FrankenPHPApp reads them at Start() time. -// FrankenPHPApp.Workers may be set by JSON config, so keep them separate. -var moduleWorkerConfigs []workerConfig - func init() { caddy.RegisterModule(FrankenPHPApp{}) caddy.RegisterModule(FrankenPHPModule{}) @@ -104,6 +100,40 @@ func (f *FrankenPHPApp) Provision(ctx caddy.Context) error { return nil } +func (f *FrankenPHPApp) generateUniqueModuleWorkerName(filepath string) string { + var i uint + filepath, _ = fastabs.FastAbs(filepath) + name := "m#" + filepath + +retry: + for _, wc := range f.Workers { + if wc.Name == name { + name = fmt.Sprintf("m#%s_%d", filepath, i) + i++ + + goto retry + } + } + + return name +} + +func (f *FrankenPHPApp) addModuleWorkers(workers ...workerConfig) ([]workerConfig, error) { + for i := range workers { + w := &workers[i] + if frankenphp.EmbeddedAppPath != "" && filepath.IsLocal(w.FileName) { + w.FileName = filepath.Join(frankenphp.EmbeddedAppPath, w.FileName) + } + if w.Name == "" { + w.Name = f.generateUniqueModuleWorkerName(w.FileName) + } else if !strings.HasPrefix(w.Name, "m#") { + w.Name = "m#" + w.Name + } + f.Workers = append(f.Workers, *w) + } + return workers, nil +} + func (f *FrankenPHPApp) Start() error { repl := caddy.NewReplacer() @@ -115,9 +145,7 @@ func (f *FrankenPHPApp) Start() error { frankenphp.WithPhpIni(f.PhpIni), frankenphp.WithMaxWaitTime(f.MaxWaitTime), } - // Add workers from FrankenPHPApp and FrankenPHPModule configurations - // f.Workers may have been set by JSON config, so keep them separate - for _, w := range append(f.Workers, moduleWorkerConfigs...) { + for _, w := range append(f.Workers) { opts = append(opts, frankenphp.WithWorkers(w.Name, repl.ReplaceKnown(w.FileName, ""), w.Num, w.Env, w.Watch)) } @@ -143,7 +171,6 @@ func (f *FrankenPHPApp) Stop() error { f.Workers = nil f.NumThreads = 0 f.MaxWaitTime = 0 - moduleWorkerConfigs = nil return nil } @@ -391,6 +418,23 @@ func (FrankenPHPModule) CaddyModule() caddy.ModuleInfo { // Provision sets up the module. func (f *FrankenPHPModule) Provision(ctx caddy.Context) error { f.logger = ctx.Slogger() + app, err := ctx.App("frankenphp") + if err != nil { + return err + } + fapp, ok := app.(*FrankenPHPApp) + if !ok { + return fmt.Errorf(`expected ctx.App("frankenphp") to return *FrankenPHPApp, got %T`, app) + } + if fapp == nil { + return fmt.Errorf(`expected ctx.App("frankenphp") to return *FrankenPHPApp, got nil`) + } + + workers, err := fapp.addModuleWorkers(f.Workers...) + if err != nil { + return err + } + f.Workers = workers if f.Root == "" { if frankenphp.EmbeddedAppPath == "" { @@ -504,25 +548,6 @@ func (f *FrankenPHPModule) ServeHTTP(w http.ResponseWriter, r *http.Request, _ c return nil } -func generateUniqueModuleWorkerName(filepath string) string { - var i uint - name := "m#" + filepath - -outer: - for { - for _, wc := range moduleWorkerConfigs { - if wc.Name == name { - name = fmt.Sprintf("m#%s_%d", filepath, i) - i++ - - continue outer - } - } - - return name - } -} - // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (f *FrankenPHPModule) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // First pass: Parse all directives except "worker" @@ -608,28 +633,14 @@ func (f *FrankenPHPModule) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { } } - if wc.Name == "" { - wc.Name = generateUniqueModuleWorkerName(wc.FileName) - } - if !strings.HasPrefix(wc.Name, "m#") { - wc.Name = "m#" + wc.Name - } - // Check if a worker with this filename already exists in this module for _, existingWorker := range f.Workers { if existingWorker.FileName == wc.FileName { return fmt.Errorf(`workers in a single "php_server" block must not have duplicate filenames: %q`, wc.FileName) } } - // Check if a worker with this name and a different environment or filename already exists - for _, existingWorker := range moduleWorkerConfigs { - if existingWorker.Name == wc.Name { - return fmt.Errorf("workers must not have duplicate names: %q", wc.Name) - } - } f.Workers = append(f.Workers, wc) - moduleWorkerConfigs = append(moduleWorkerConfigs, wc) } } } diff --git a/caddy/caddy_test.go b/caddy/caddy_test.go index 1bf6fc066b..9d3a9a0132 100644 --- a/caddy/caddy_test.go +++ b/caddy/caddy_test.go @@ -31,8 +31,6 @@ func TestPHP(t *testing.T) { admin localhost:2999 http_port `+testPort+` https_port 9443 - - frankenphp } localhost:`+testPort+` { @@ -63,8 +61,6 @@ func TestLargeRequest(t *testing.T) { admin localhost:2999 http_port `+testPort+` https_port 9443 - - frankenphp } localhost:`+testPort+` { @@ -182,8 +178,6 @@ func TestNamedModuleWorkers(t *testing.T) { { skip_install_trust admin localhost:2999 - - frankenphp } http://localhost:`+testPort+` { @@ -383,8 +377,6 @@ func TestPHPServerDirective(t *testing.T) { admin localhost:2999 http_port `+testPort+` https_port 9443 - - frankenphp } localhost:`+testPort+` { @@ -406,8 +398,6 @@ func TestPHPServerDirectiveDisableFileServer(t *testing.T) { admin localhost:2999 http_port `+testPort+` https_port 9443 - - frankenphp order php_server before respond } @@ -434,8 +424,6 @@ func TestMetrics(t *testing.T) { http_port `+testPort+` https_port 9443 metrics - - frankenphp } localhost:`+testPort+` { @@ -800,7 +788,6 @@ func TestAllDefinedServerVars(t *testing.T) { skip_install_trust admin localhost:2999 http_port `+testPort+` - frankenphp } localhost:`+testPort+` { route { diff --git a/caddy/config_test.go b/caddy/config_test.go index 9a4c9aa230..7bcbbfc27b 100644 --- a/caddy/config_test.go +++ b/caddy/config_test.go @@ -7,11 +7,6 @@ import ( "github.com/stretchr/testify/require" ) -// resetModuleWorkers resets the moduleWorkerConfigs slice for testing -func resetModuleWorkers() { - moduleWorkerConfigs = make([]workerConfig, 0) -} - func TestModuleWorkerDuplicateFilenamesFail(t *testing.T) { // Create a test configuration with duplicate worker filenames configWithDuplicateFilenames := ` @@ -38,53 +33,6 @@ func TestModuleWorkerDuplicateFilenamesFail(t *testing.T) { // Verify that an error was returned require.Error(t, err, "Expected an error when two workers in the same module have the same filename") require.Contains(t, err.Error(), "must not have duplicate filenames", "Error message should mention duplicate filenames") - resetModuleWorkers() -} - -func TestModuleWorkersDuplicateNameFail(t *testing.T) { - // Create a test configuration with a worker name - configWithWorkerName1 := ` - { - php_server { - worker { - name test-worker - file ../testdata/worker-with-env.php - num 1 - } - } - }` - - // Parse the first configuration - d1 := caddyfile.NewTestDispenser(configWithWorkerName1) - module1 := &FrankenPHPModule{} - - // Unmarshal the first configuration - err := module1.UnmarshalCaddyfile(d1) - require.NoError(t, err, "First module should be configured without errors") - - // Create a second test configuration with the same worker name - configWithWorkerName2 := ` - { - php_server { - worker { - name test-worker - file ../testdata/worker-with-env.php - num 1 - } - } - }` - - // Parse the second configuration - d2 := caddyfile.NewTestDispenser(configWithWorkerName2) - module2 := &FrankenPHPModule{} - - // Unmarshal the second configuration - err = module2.UnmarshalCaddyfile(d2) - - // Verify that an error was returned - require.Error(t, err, "Expected an error when two workers have the same name, but different environments") - require.Contains(t, err.Error(), "must not have duplicate names", "Error message should mention duplicate names") - resetModuleWorkers() } func TestModuleWorkersWithDifferentFilenames(t *testing.T) { @@ -111,8 +59,6 @@ func TestModuleWorkersWithDifferentFilenames(t *testing.T) { require.Len(t, module.Workers, 2, "Expected two workers to be added to the module") require.Equal(t, "../testdata/worker-with-env.php", module.Workers[0].FileName, "First worker should have the correct filename") require.Equal(t, "../testdata/worker-with-counter.php", module.Workers[1].FileName, "Second worker should have the correct filename") - - resetModuleWorkers() } func TestModuleWorkersDifferentNamesSucceed(t *testing.T) { @@ -130,6 +76,7 @@ func TestModuleWorkersDifferentNamesSucceed(t *testing.T) { // Parse the first configuration d1 := caddyfile.NewTestDispenser(configWithWorkerName1) + app := &FrankenPHPApp{} module1 := &FrankenPHPModule{} // Unmarshal the first configuration @@ -158,12 +105,15 @@ func TestModuleWorkersDifferentNamesSucceed(t *testing.T) { // Verify that no error was returned require.NoError(t, err, "Expected no error when two workers have different names") - // Verify that both workers were added to moduleWorkerConfigs - require.Len(t, moduleWorkerConfigs, 2, "Expected two workers to be added to moduleWorkerConfigs") - require.Equal(t, "m#test-worker-1", moduleWorkerConfigs[0].Name, "First worker should have the correct name") - require.Equal(t, "m#test-worker-2", moduleWorkerConfigs[1].Name, "Second worker should have the correct name") + _, err = app.addModuleWorkers(module1.Workers...) + require.NoError(t, err, "Expected no error when adding the first module workers") + _, err = app.addModuleWorkers(module2.Workers...) + require.NoError(t, err, "Expected no error when adding the second module workers") - resetModuleWorkers() + // Verify that both workers were added + require.Len(t, app.Workers, 2, "Expected two workers in the app") + require.Equal(t, "m#test-worker-1", app.Workers[0].Name, "First worker should have the correct name") + require.Equal(t, "m#test-worker-2", app.Workers[1].Name, "Second worker should have the correct name") } func TestModuleWorkerWithEnvironmentVariables(t *testing.T) { @@ -198,8 +148,6 @@ func TestModuleWorkerWithEnvironmentVariables(t *testing.T) { require.Len(t, module.Workers[0].Env, 2, "Expected two environment variables") require.Equal(t, "production", module.Workers[0].Env["APP_ENV"], "APP_ENV should be set to production") require.Equal(t, "true", module.Workers[0].Env["DEBUG"], "DEBUG should be set to true") - - resetModuleWorkers() } func TestModuleWorkerWithWatchConfiguration(t *testing.T) { @@ -236,8 +184,6 @@ func TestModuleWorkerWithWatchConfiguration(t *testing.T) { require.Equal(t, "./**/*.{php,yaml,yml,twig,env}", module.Workers[0].Watch[0], "First watch pattern should be the default") require.Equal(t, "./src/**/*.php", module.Workers[0].Watch[1], "Second watch pattern should match the configuration") require.Equal(t, "./config/**/*.yaml", module.Workers[0].Watch[2], "Third watch pattern should match the configuration") - - resetModuleWorkers() } func TestModuleWorkerWithCustomName(t *testing.T) { @@ -256,6 +202,7 @@ func TestModuleWorkerWithCustomName(t *testing.T) { // Parse the configuration d := caddyfile.NewTestDispenser(configWithCustomName) module := &FrankenPHPModule{} + app := &FrankenPHPApp{} // Unmarshal the configuration err := module.UnmarshalCaddyfile(d) @@ -267,8 +214,9 @@ func TestModuleWorkerWithCustomName(t *testing.T) { require.Len(t, module.Workers, 1, "Expected one worker to be added to the module") require.Equal(t, "../testdata/worker-with-env.php", module.Workers[0].FileName, "Worker should have the correct filename") - // Verify that the worker was added to moduleWorkerConfigs with the m# prefix - require.Equal(t, "m#custom-worker-name", module.Workers[0].Name, "Worker should have the custom name") - - resetModuleWorkers() + // Verify that the worker was added to app.Workers with the m# prefix + module.Workers, err = app.addModuleWorkers(module.Workers...) + require.NoError(t, err, "Expected no error when adding the worker to the app") + require.Equal(t, "m#custom-worker-name", module.Workers[0].Name, "Worker should have the custom name, prefixed with m#") + require.Equal(t, "m#custom-worker-name", app.Workers[0].Name, "Worker should have the custom name, prefixed with m#") } diff --git a/docs/cn/config.md b/docs/cn/config.md index 18949c95d6..d20853c403 100644 --- a/docs/cn/config.md +++ b/docs/cn/config.md @@ -1,4 +1,4 @@ -# 配置 +# 配置 FrankenPHP,Caddy 以及 Mercure 和 Vulcain 模块可以使用 [Caddy 支持的格式](https://caddyserver.com/docs/getting-started#your-first-config) 进行配置。 @@ -39,16 +39,11 @@ FrankenPHP 安装 (.rpm 或 .deb): ## Caddyfile 配置 -要注册 FrankenPHP 执行器,必须设置 `frankenphp` [全局选项](https://caddyserver.com/docs/caddyfile/concepts#global-options),然后可以在站点块中使用 `php_server` 或 `php` [HTTP 指令](https://caddyserver.com/docs/caddyfile/concepts#directives) 来为您的 PHP 应用程序提供服务。 +可以在站点块中使用 `php_server` 或 `php` [HTTP 指令](https://caddyserver.com/docs/caddyfile/concepts#directives) 来为您的 PHP 应用程序提供服务。 最小示例: ```caddyfile -{ - # 启用 FrankenPHP - frankenphp -} - localhost { # 启用压缩(可选) encode zstd br gzip @@ -57,7 +52,8 @@ localhost { } ``` -或者,可以在全局选项下指定要创建的线程数和要从服务器启动的 [worker 脚本](worker.md)。 +您也可以使用全局选项显式配置 FrankenPHP: +`frankenphp` [全局选项](https://caddyserver.com/docs/caddyfile/concepts#global-options) 可用于配置 FrankenPHP。 ```caddyfile { @@ -89,21 +85,18 @@ localhost { 如果在同一服务器上运行多个应用,还可以定义多个 worker: ```caddyfile -{ - frankenphp { - worker /path/to/app/public/index.php - worker /path/to/other/public/index.php - } -} - app.example.com { - root /path/to/app/public - php_server + php_server { + root /path/to/app/public + worker index.php + } } other.example.com { - root /path/to/other/public - php_server + php_server { + root /path/to/other/public + worker index.php + } } # ... ``` @@ -139,9 +132,18 @@ route { ```caddyfile php_server [] { root # 设置站点的根目录。默认值:`root` 指令。 - split_path # 设置用于将 URI 拆分为两部分的子字符串。第一个匹配的子字符串将用于从路径中拆分“路径信息”。第一个部分以匹配的子字符串为后缀,并将假定为实际资源(CGI 脚本)名称。第二部分将设置为PATH_INFO,供脚本使用。默认值:`.php` + split_path # 设置用于将 URI 拆分为两部分的子字符串。第一个匹配的子字符串将用于从路径中拆分"路径信息"。第一个部分以匹配的子字符串为后缀,并将假定为实际资源(CGI 脚本)名称。第二部分将设置为PATH_INFO,供脚本使用。默认值:`.php` resolve_root_symlink false # 禁用将 `root` 目录在符号链接时将其解析为实际值(默认启用)。 env # 设置额外的环境变量,可以设置多个环境变量。 + file_server off # 禁用内置的 file_server 指令。 + worker { # 创建特定于此服务器的 worker。可以为多个 worker 多次指定。 + file # 设置 worker 脚本的路径,可以相对于 php_server 根目录 + num # 设置要启动的 PHP 线程数,默认为可用 CPU 数的 2 倍 + name # 为 worker 设置名称,用于日志和指标。默认值:worker 文件的绝对路径。在 php_server 块中定义时始终以 m# 开头。 + watch # 设置要监视文件更改的路径。可以为多个路径多次指定。 + env # 将额外的环境变量设置为给定值。可以为多个环境变量多次指定。此 worker 的环境变量也从 php_server 父级继承,但可以在此处覆盖。 + } + worker # 也可以像在全局 frankenphp 块中一样使用简短形式。 } ``` diff --git a/docs/config.md b/docs/config.md index 09a225e6d4..7285914505 100644 --- a/docs/config.md +++ b/docs/config.md @@ -42,16 +42,11 @@ RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini ## Caddyfile Config -To register the FrankenPHP executor, the `frankenphp` [global option](https://caddyserver.com/docs/caddyfile/concepts#global-options) must be set, then the `php_server` or the `php` [HTTP directives](https://caddyserver.com/docs/caddyfile/concepts#directives) may be used within the site blocks to serve your PHP app. +The `php_server` or the `php` [HTTP directives](https://caddyserver.com/docs/caddyfile/concepts#directives) may be used within the site blocks to serve your PHP app. Minimal example: ```caddyfile -{ - # Enable FrankenPHP - frankenphp -} - localhost { # Enable compression (optional) encode zstd br gzip @@ -60,7 +55,8 @@ localhost { } ``` -Optionally, the number of threads to create and [worker scripts](worker.md) to start with the server can be specified under the global option. +You can also explicitly configure FrankenPHP using the global option: +The `frankenphp` [global option](https://caddyserver.com/docs/caddyfile/concepts#global-options) can be used to configure FrankenPHP. ```caddyfile { @@ -97,21 +93,18 @@ Alternatively, you may use the one-line short form of the `worker` option: You can also define multiple workers if you serve multiple apps on the same server: ```caddyfile -{ - frankenphp { - worker /path/to/app/public/index.php - worker /path/to/other/public/index.php - } -} - app.example.com { - root /path/to/app/public - php_server + php_server { + root /path/to/app/public + worker index.php + } } other.example.com { - root /path/to/other/public - php_server + php_server { + root /path/to/other/public + worker index.php + } } # ... @@ -154,6 +147,14 @@ php_server [] { resolve_root_symlink false # Disables resolving the `root` directory to its actual value by evaluating a symbolic link, if one exists (enabled by default). env # Sets an extra environment variable to the given value. Can be specified more than once for multiple environment variables. file_server off # Disables the built-in file_server directive. + worker { # Creates a worker specific to this server. Can be specified more than once for multiple workers. + file # Sets the path to the worker script, can be relative to the php_server root + num # Sets the number of PHP threads to start, defaults to 2x the number of available + name # Sets the name for the worker, used in logs and metrics. Default: absolute path of worker file. Always starts with m# when defined in a php_server block. + watch # Sets the path to watch for file changes. Can be specified more than once for multiple paths. + env # Sets an extra environment variable to the given value. Can be specified more than once for multiple environment variables. Environment variables for this worker are also inherited from the php_server parent, but can be overwritten here. + } + worker # Can also use the short form like in the global frankenphp block. } ``` diff --git a/docs/fr/config.md b/docs/fr/config.md index 417b31a68e..c43023fc3b 100644 --- a/docs/fr/config.md +++ b/docs/fr/config.md @@ -1,4 +1,4 @@ -# Configuration +# Configuration FrankenPHP, Caddy ainsi que les modules Mercure et Vulcain peuvent être configurés en utilisant [les formats pris en charge par Caddy](https://caddyserver.com/docs/getting-started#your-first-config). @@ -41,16 +41,11 @@ Binaire statique : ## Configuration du Caddyfile -Pour enregistrer l'exécutable de FrankenPHP, l'[option globale](https://caddyserver.com/docs/caddyfile/concepts#global-options) `frankenphp` doit être définie, puis les [directives HTTP](https://caddyserver.com/docs/caddyfile/concepts#directives) `php_server` ou `php` peuvent être utilisées dans les blocs de site pour servir votre application PHP. +Les [directives HTTP](https://caddyserver.com/docs/caddyfile/concepts#directives) `php_server` ou `php` peuvent être utilisées dans les blocs de site pour servir votre application PHP. Exemple minimal : ```caddyfile -{ - # Activer FrankenPHP - frankenphp -} - localhost { # Activer la compression (optionnel) encode zstd br gzip @@ -59,14 +54,15 @@ localhost { } ``` -En option, le nombre de threads à créer et les [workers](worker.md) à démarrer avec le serveur peuvent être spécifiés sous l'option globale. +Vous pouvez également configurer explicitement FrankenPHP en utilisant l'option globale : +L'[option globale](https://caddyserver.com/docs/caddyfile/concepts#global-options) `frankenphp` peut être utilisée pour configurer FrankenPHP. ```caddyfile { frankenphp { num_threads # Définit le nombre de threads PHP à démarrer. Par défaut : 2x le nombre de CPUs disponibles. max_threads # Limite le nombre de threads PHP supplémentaires qui peuvent être démarrés au moment de l'exécution. Valeur par défaut : num_threads. Peut être mis à 'auto'. - max_wait_time # Définit le temps maximum pendant lequel une requête peut attendre un thread PHP libre avant d'être interrompue. Valeur par défaut : désactivé. + max_wait_time # Définit le temps maximum pendant lequel une requête peut attendre un thread PHP libre avant d'être interrompue. Valeur par défaut : désactivé. php_ini Définit une directive php.ini. Peut être utilisé plusieurs fois pour définir plusieurs directives. worker { file # Définit le chemin vers le script worker. @@ -96,21 +92,18 @@ Vous pouvez également utiliser la forme courte de l'option worker en une seule Vous pouvez aussi définir plusieurs workers si vous servez plusieurs applications sur le même serveur : ```caddyfile -{ - frankenphp { - worker /path/to/app/public/index.php - worker /path/to/other/public/index.php - } -} - app.example.com { - root /path/to/app/public - php_server + php_server { + root /path/to/app/public + worker index.php + } } other.example.com { - root /path/to/other/public - php_server + php_server { + root /path/to/other/public + worker index.php + } } # ... @@ -153,6 +146,14 @@ php_server [] { resolve_root_symlink false # Désactive la résolution du répertoire `root` vers sa valeur réelle en évaluant un lien symbolique, s'il existe (activé par défaut). env # Définit une variable d'environnement supplémentaire avec la valeur donnée. Peut être spécifié plusieurs fois pour plusieurs variables d'environnement. file_server off # Désactive la directive file_server intégrée. + worker { # Crée un worker spécifique à ce serveur. Peut être spécifié plusieurs fois pour plusieurs workers. + file # Définit le chemin vers le script worker, peut être relatif à la racine du php_server + num # Définit le nombre de threads PHP à démarrer, par défaut 2x le nombre de CPUs disponibles + name # Définit le nom du worker, utilisé dans les journaux et les métriques. Défaut : chemin absolu du fichier du worker. Commence toujours par m# lorsqu'il est défini dans un bloc php_server. + watch # Définit le chemin d'accès à surveiller pour les modifications de fichiers. Peut être spécifié plusieurs fois pour plusieurs chemins. + env # Définit une variable d'environnement supplémentaire avec la valeur donnée. Peut être spécifié plusieurs fois pour plusieurs variables d'environnement. Les variables d'environnement pour ce worker sont également héritées du parent php_server, mais peuvent être écrasées ici. + } + worker # Peut également utiliser la forme courte comme dans le bloc frankenphp global. } ``` diff --git a/docs/ru/config.md b/docs/ru/config.md index b9820d0231..2ca7335978 100644 --- a/docs/ru/config.md +++ b/docs/ru/config.md @@ -1,4 +1,4 @@ -# Конфигурация +# Конфигурация FrankenPHP, Caddy, а также модули Mercure и Vulcain могут быть настроены с использованием [конфигурационных форматов, поддерживаемых Caddy](https://caddyserver.com/docs/getting-started#your-first-config). @@ -41,16 +41,11 @@ RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini ## Конфигурация Caddyfile -Для настройки FrankenPHP установите [глобальную опцию](https://caddyserver.com/docs/caddyfile/concepts#global-options) frankenphp. После этого можно использовать [HTTP-директивы](https://caddyserver.com/docs/caddyfile/concepts#directives) `php_server` или `php` для обработки вашего PHP-приложения. +[HTTP-директивы](https://caddyserver.com/docs/caddyfile/concepts#directives) `php_server` или `php` могут быть использованы в блоках сайта для обработки вашего PHP-приложения. Минимальный пример: ```caddyfile -{ - # Включить FrankenPHP - frankenphp -} - localhost { # Включить сжатие (опционально) encode zstd br gzip @@ -59,7 +54,8 @@ localhost { } ``` -Опционально можно указать количество потоков и [worker-скриптов](worker.md), которые запускаются вместе с сервером: +Вы также можете явно настроить FrankenPHP с помощью глобальной опции: +[Глобальная опция](https://caddyserver.com/docs/caddyfile/concepts#global-options) `frankenphp` может быть использована для настройки FrankenPHP. ```caddyfile { @@ -92,21 +88,18 @@ localhost { Вы также можете определить несколько workers, если обслуживаете несколько приложений на одном сервере: ```caddyfile -{ - frankenphp { - worker /path/to/app/public/index.php - worker /path/to/other/public/index.php - } -} - app.example.com { - root /path/to/app/public - php_server + php_server { + root /path/to/app/public + worker index.php + } } other.example.com { - root /path/to/other/public - php_server + php_server { + root /path/to/other/public + worker index.php + } } # ... @@ -146,6 +139,14 @@ php_server [] { resolve_root_symlink false # Отключает разрешение символьных ссылок для `root` (включено по умолчанию). env # Устанавливает дополнительные переменные окружения. Можно указать несколько раз для разных переменных. file_server off # Отключает встроенную директиву file_server. + worker { # Создает worker, специфичный для этого сервера. Можно указать несколько раз для разных workers. + file # Указывает путь к worker-скрипту, может быть относительным к корню php_server + num # Указывает количество потоков PHP. По умолчанию: 2x от числа доступных CPU. + name # Устанавливает имя для worker, используемое в логах и метриках. По умолчанию: абсолютный путь к файлу worker. Всегда начинается с m# при определении в блоке php_server. + watch # Указывает путь для отслеживания изменений файлов. Можно указать несколько раз для разных путей. + env # Устанавливает дополнительную переменную окружения. Можно указать несколько раз для разных переменных. Переменные окружения для этого worker также наследуются от родительского php_server, но могут быть переопределены здесь. + } + worker # Также можно использовать краткую форму как в глобальном блоке frankenphp. } ``` diff --git a/docs/tr/config.md b/docs/tr/config.md index 18c7b1b0ed..cf19a2ca31 100644 --- a/docs/tr/config.md +++ b/docs/tr/config.md @@ -1,4 +1,4 @@ -# Konfigürasyon +# Konfigürasyon FrankenPHP, Caddy'nin yanı sıra Mercure ve Vulcain modülleri [Caddy tarafından desteklenen formatlar](https://caddyserver.com/docs/getting-started#your-first-config) kullanılarak yapılandırılabilir. @@ -41,16 +41,11 @@ Statik ikili: ## Caddyfile Konfigürasyonu -FrankenPHP yürütücüsünü kaydetmek için `frankenphp` [global seçenek](https://caddyserver.com/docs/caddyfile/concepts#global-options) ayarlanmalıdır, ardından PHP uygulamanızı sunmak için site blokları içinde `php_server` veya `php` [HTTP yönergeleri](https://caddyserver.com/docs/caddyfile/concepts#directives) kullanılabilir. +PHP uygulamanızı sunmak için site blokları içinde `php_server` veya `php` [HTTP yönergeleri](https://caddyserver.com/docs/caddyfile/concepts#directives) kullanılabilir. Minimal örnek: ```caddyfile -{ - # FrankenPHP'yi aktif et - frankenphp -} - localhost { # Sıkıştırmayı etkinleştir (isteğe bağlı) encode zstd br gzip @@ -59,7 +54,8 @@ localhost { } ``` -İsteğe bağlı olarak, oluşturulacak iş parçacığı sayısı ve sunucuyla birlikte başlatılacak [işçi betikleri] (worker.md) global seçenek altında belirtilebilir. +FrankenPHP'yi global seçenek kullanarak açıkça yapılandırabilirsiniz: +`frankenphp` [global seçenek](https://caddyserver.com/docs/caddyfile/concepts#global-options) FrankenPHP'yi yapılandırmak için kullanılabilir. ```caddyfile { @@ -91,21 +87,18 @@ Alternatif olarak, `worker` seçeneğinin tek satırlık kısa formunu kullanabi Aynı sunucuda birden fazla uygulamaya hizmet veriyorsanız birden fazla işçi de tanımlayabilirsiniz: ```caddyfile -{ - frankenphp { - worker /path/to/app/public/index.php - worker /path/to/other/public/index.php - } -} - app.example.com { - root /path/to/app/public - php_server + php_server { + root /path/to/app/public + worker index.php + } } other.example.com { - root /path/to/other/public - php_server + php_server { + root /path/to/other/public + worker index.php + } } # ... @@ -145,6 +138,15 @@ php_server [] { split_path # URI'yi iki parçaya bölmek için alt dizgeleri ayarlar. İlk eşleşen alt dizge "yol bilgisini" yoldan ayırmak için kullanılır. İlk parça eşleşen alt dizeyle sonlandırılır ve gerçek kaynak (CGI betiği) adı olarak kabul edilir. İkinci parça betiğin kullanması için PATH_INFO olarak ayarlanacaktır. Varsayılan: `.php` resolve_root_symlink false # Varsa, sembolik bir bağlantıyı değerlendirerek `root` dizininin gerçek değerine çözümlenmesini devre dışı bırakır (varsayılan olarak etkindir). env # Ek bir ortam değişkenini verilen değere ayarlar. Birden fazla ortam değişkeni için birden fazla kez belirtilebilir. + file_server off # Yerleşik file_server yönergesini devre dışı bırakır. + worker { # Bu sunucuya özgü bir worker oluşturur. Birden fazla worker için birden fazla kez belirtilebilir. + file # Worker betiğinin yolunu ayarlar, php_server köküne göre göreceli olabilir + num # Başlatılacak PHP iş parçacığı sayısını ayarlar, varsayılan değer mevcut CPU çekirdek sayısının 2 katıdır + name # Worker için günlüklerde ve metriklerde kullanılan bir ad ayarlar. Varsayılan: worker dosyasının mutlak yolu. Bir php_server bloğunda tanımlandığında her zaman m# ile başlar. + watch # Dosya değişikliklerini izlemek için yolu ayarlar. Birden fazla yol için birden fazla kez belirtilebilir. + env # Ek bir ortam değişkenini verilen değere ayarlar. Birden fazla ortam değişkeni için birden fazla kez belirtilebilir. Bu worker için ortam değişkenleri ayrıca php_server üst öğesinden devralınır, ancak burada geçersiz kılınabilir. + } + worker # Global frankenphp bloğundaki gibi kısa formu da kullanabilirsiniz. } ```