makinacorpus/preferences-bundle

首选项是用户管理的配置变量,我们不能依赖于容器参数或环境变量。

1.1.1 2023-09-28 15:29 UTC

This package is auto-updated.

Last update: 2024-09-08 15:40:29 UTC


README

首选项是旨在由用户管理的配置变量,我们不能依赖于容器参数或环境变量。

此捆绑包提供简单的API用于

  • 定义首选项变量模式,包括变量名、类型和描述。

  • 由容器作为环境变量读取,以便可以使用这些变量作为服务参数。

  • 一种表单类型,它处理所有基本类型(int、type、string)作为集合或单值变量,您可以在任何表单中使用。

  • 使用 makinacorpus/goat-query 存储用户值的具体实现。

  • 用于 symfony/messengermakinacorpus/goatmakinacorpus/corebus 的总线处理程序和消息。

  • 用于读取项目配置中定义的模式接口。

  • 用于读取值的接口。

设置

此软件包依赖于 makinacorpus/goat-query

简单地安装此软件包

composer require makinacorpus/preferences-bundle

然后将捆绑包添加到您的 config/bundles.php 文件中

<?php

return [
    // ... Your other bundles.
    MakinaCorpus\Preferences\PreferencesBundle::class => ['all' => true],
];

定义自定义模式

您可以定义一个模式

preferences:
    schema:
        app.domain.some_variable:
            label: Some variable
            description: Uncheck this value to deactive this feature
            type: bool
            collection: false
            default: true

条目数量不限。唯一的限制是内存,因为整个定义将作为一个裸PHP数组注入到默认数组模式实现中。

请注意,由于Symfony环境变量处理器严格验证变量名称,所有非字母数字和非 _ 字符都会使环境变量处理器失败。如果您计划通过环境变量将变量注入到服务中,您必须相应地命名变量,例如

preferences:
    schema:
        app_domain_some_variable:
            label: Some variable
            description: Uncheck this value to deactive this feature
            type: bool
            collection: false
            default: true

所有选项都是可选的。默认值是

preferences:
    enabled: true
    schema:
        app_domain_some_variable:
            label: null
            description: null
            type: string
            allowed_values: null
            collection: false
            hashmap: false
            default: null

可以在每个变量定义上设置的参数

  • label: 是一个可读的短名称,
  • description: 是一个可读的长描述,
  • type: 可以是以下之一: stringboolintfloat,
  • allowed_values: 是一个任意值的数组,用于后续验证,
  • collection: 如果设置为 true,则允许此变量的多个值,
  • hashmap: 如果设置为 true,则允许键,如果 collectionfalse,则忽略此设置,
  • default: 如果用户未配置,则为任意默认值。

用法

将首选项作为服务参数注入

此软件包定义了一个 EnvVarProcessorInterface 实现,允许将首选项注入为环境变量,例如

services:
    my_service:
        class: App\Some\Class
        arguments: ["%env(preference:app_domain_some_variable)%"]

在其他服务中使用首选项服务。

使用 MakinaCorpus\Preferences\Preferences 类型提示注入的参数,然后使用 get(string $name): mixed 方法获取值。

长期路线图

  • 添加新的存储库实现(Redis、PDO、其他...)。
  • 正确实现总线处理程序。
  • 实现PHP模式转储器。