imatic / config-bundle
Imatic Config Bundle
v5.3.4
2023-05-29 13:32 UTC
Requires
- php: >=7.4
- ext-json: *
- doctrine/doctrine-bundle: ^2.4
- doctrine/orm: ^2.7
- symfony/form: 4.4|^5.3
- symfony/framework-bundle: ^4.4|^5.3
- symfony/translation: ^4.4|^5.3
- symfony/twig-bundle: ^4.4|^5.3
- symfony/validator: ^4.4|^5.3
Requires (Dev)
- doctrine/doctrine-fixtures-bundle: ^3.4
- friendsofphp/php-cs-fixer: ^3.2
- imatic/testing: ^6.0
- symfony/browser-kit: ^4.4|^5.3
- symfony/css-selector: ^4.4|^5.3
- symfony/phpunit-bridge: ^4.4|^5.3
- symfony/security-bundle: ^4.4|^5.3
- symfony/yaml: ^4.4|^5.3
This package is auto-updated.
Last update: 2024-09-29 16:37:54 UTC
README
ImaticConfigBundle 提供了一种简单的方式来管理存储在数据库中的配置。
安装
composer require imatic/config-bundle
启用包
如果您不使用 Symfony Flex,请手动注册包
// in config/bundles.php return [ // ... Imatic\Bundle\ConfigBundle\ImaticConfigBundle::class => ['all' => true], ];
创建配置表
// src/Entity/Config.php <?php declare(strict_types=1); namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity */ class Config extends \Imatic\Bundle\ConfigBundle\Entity\Config { }
如果表未在默认模式中定义,您需要指定在包配置中的实体。
#config/packages/imatic_config.yaml imatic_config: entity_class: App\Entity\Config
使用方法
配置定义在扩展 ProviderInterface 的类中。
// src/Config/ConfigProvider.php namespace App\Config; use Imatic\Bundle\ConfigBundle\Provider\Definition; use Imatic\Bundle\ConfigBundle\Provider\ProviderInterface; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Validator\Constraints as Assert; final class ConfigProvider implements ProviderInterface { public function getDefinitions(): array { return [ new Definition('value', TextType::class, [ 'constraints' => [ new Assert\NotBlank(), ], ]), ]; } }
配置必须注册为服务并标记为 imatic_config.provider
。如果您使用默认的 Symfony services.yaml 配置,这已经通过自动配置为您完成。
您可以将配置组织在多个文件中,具有不同的别名。每个配置值都以别名名称为前缀。默认别名名称是 config
。
读取配置
要读取配置值,通过类型提示 ConfigManagerInterface 获取 ConfigManager 实例。
// src/Controller/ConfigController.php namespace App\Controller; use Imatic\Bundle\ConfigBundle\Config\ConfigManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; final class ConfigController extends AbstractController { public function getConfig(ConfigManagerInterface $config) { $value = $config->getValue('config.value'); // ... } }
在 Twig 模板中的使用
此包中的 Twig 扩展支持直接在模板中读取配置。
{{ imatic_config_value('config.value') }}
管理配置
您只需要注册包的路由配置,管理就会在 imatic_config_config
路由下可用。
#config/routes/imatic_config.yaml imatic_config: resource: '@ImaticConfigBundle/Resources/config/routing.xml' prefix: /
它假定您的项目基本模板是 base.html.twig
。如果您使用其他基本模板,您需要将其指定在包配置中。
#config/packages/imatic_config.yaml imatic_config: templates: base: 'base/template.html.twig'