2017 © Pedro Peláez
 

symfony-bundle settings-manager-bundle

Provides a nice way to define variables and inject them into application parts

image

helis/settings-manager-bundle

Provides a nice way to define variables and inject them into application parts

  • Thursday, July 26, 2018
  • by HelisLT
  • Repository
  • 4 Watchers
  • 14 Stars
  • 336 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 5 Forks
  • 0 Open issues
  • 5 Versions
  • 0 % Grown

The README.md

Helis Settings Manager Bundle

Provides a nice way to define variables and inject them into application parts., (*1)

  • Supporting bool, string, int, float, array as setting values.
  • Multiple providers.
  • User interface.

Latest Stable Version License, (*2)

Jump to

Quick start

  1. composer require helis/settings-manager-bundle, (*3)

  2. Register bundle to AppKernel.php (Symfony3) or config/bundles.php (Symfony4), (*4)

<?php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        return [
            new Helis\SettingsManagerBundle\HelisSettingsManagerBundle(),
        ];
    }
}
  1. Add an example configuration to app/config/config.yml (Symfony3) or config/packages/settings_manager.yaml (Symfony4)
helis_settings_manager:
    settings:
        - name: foo
          description: 'foo desc'
          type: bool
          data: false
          tags:
              - 'super_switch'

        - name: baz
          description: 'master toggle for awesome new feature'
          type: string
          data: fish
          tags:
              - 'experimental'
              - 'poo'
  1. Now, the easiest way to get settings in your services is by using SettingsRouterAwareTrait. The service will be automatically injected by autowire. Then just ask for setting:
use Helis\SettingsManagerBundle\Settings\Traits\SettingsRouterAwareTrait;

class MuchAmazingService
{
    use SettingsRouterAwareTrait;

    public function doSmth()
    {
        if ($this->settingsRouter->getBool('foo')) {
            // do it
        }

        // just do it
    }
}

Usage

To get settings into your services, you have a few choices:, (*5)

SettingsRouter

SettingsRouter is pretty straight-forward. It has one main method, called $settingsRouter->get($settingName, $default = null), which returns a setting of any type. If the setting is missing, default value will be returned. Other getters are aliases for get but with declared return types and appropriate default values., (*6)

Method name Default value Declared return type
getString '' string
getBool false bool
getInt 0 int
getFloat 0.0 float
getArray [] array

Throw exception on miss

In some cases throwing exception if setting not found might be desired behaviour. For this purpose, SettingsRouter has mustGet($settingName) and mustGet...($settingName) for each aliased getter., (*7)

Method name Declared return type
mustGetString string
mustGetBool bool
mustGetInt int
mustGetFloat float
mustGetArray array

Service Tag

If you don't want to inject SettingsRouter or wish for a cleaner service, service tags are here to help. First of all, the service must have a setter, which can be used to inject a setting value. For bool values, the bundle provides the SwitchableTrait, which adds setEnabled and isEnabled methods. Then add a tag on your service with attributes setting for setting name and method for method name. Example:, (*8)

AppBundle\Service\AmazingService:
    tags:
        - { name: settings_manager.setting_aware, setting: foo, method: setEnabled }

or the must version, (*9)

AppBundle\Service\AmazingService:
    tags:
        - { name: settings_manager.setting_aware, setting: foo, method: setEnabled, must: true }

Models

Helis\SettingsManagerBundle\Model\SettingModel

Base setting model., (*10)

Property Type Description
$name string Setting name
$description string Setting descrption
$domain DomainModel Domain model
$tags Collection[Tag] Collection of tags
$type Enum[Type] Determines setting value type
$data array Holds actual value for setting
$providerName string Internal field to know from which provider this setting is

Helis\SettingsManagerBundle\Model\DomainModel

Domain is like a group for settings. Setting cannot exist without domain. The default is named default, which is also always enabled. Domain can hold only one setting with the same name. Settings with the same names must be in different domains. When a setting is requested, the one from a higher priority domain will be returned., (*11)

Property Type Description
$name string Domain name
$priority int (default: 0) Domain priority
$enabled bool (default: false) Is domain enabled indication
$readOnly bool (default: false) is domain only readable indication

Helis\SettingsManagerBundle\Model\Type

Enum which holds supported types for setting. Values:, (*12)

  • STRING
  • BOOL
  • INT
  • FLOAT
  • YAML
  • CHOICE

Setting providers

Settings can be pulled from multiple sources. Currently, the bundle comes with 4 settings providers. They can be configured and prioritized. If a setting with the same name will come from >1 providers, setting from provider with higher priority will override settings from lower priority providers., (*13)

Settings can be easily mutated in providers using user interface., (*14)

Settings providers:, (*15)

And additional decorating providers:, (*16)

Simple settings provider

Helis\SettingsManagerBundle\Provider\SimpleSettingsProvider, (*17)

This is a provider, which only holds settings collections. Currently, it's being used to hold settings from configuration, but many more can be configured., (*18)

To configure additional simple providers, factory is provided because provider can only accept already denormalized objects., (*19)

Configuration example:, (*20)

setting_provider_factory.foo:
    class: Helis\SettingsManagerBundle\Provider\Factory\SimpleSettingsProviderFactory
    arguments:
        $serializer: '@settings_manager.serializer'
        $normalizedData:
            -
                - name: foo
                  description: 'foo desc'
                  type: bool
                  domain: { name: default } 
                  data: { value: false }
                  tags: [{ name: 'super_switch' }]
    tags:
        - { name: settings_manager.provider_factory, provider: foo, priority: 10 }

DoctrineORM settings provider

Helis\SettingsManagerBundle\Provider\DoctrineOrmSettingsProvider, (*21)

This is a provider which reads and saves settings using EntityManagerInterface., (*22)

Required libraries:, (*23)

composer require doctrine/orm, (*24)

Configuration example:, (*25)

  1. Doctrine configuration
# Symfony3, app/config/config.yml
# Symfony4, config/packages/doctrine.yaml
doctrine:
    orm:
        mappings:
            HelisSettingsManagerBundle:
                type: xml
                is_bundle: true
                dir: "Resources/config/doctrine"
                alias: HelisSettingsManagerBundle
                prefix: Helis\SettingsManagerBundle
  1. Create setting entity
<?php
declare(strict_types=1);

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Helis\SettingsManagerBundle\Model\SettingModel;

#[ORM\Entity()]
#[ORM\Table(name: "setting")]
class Setting extends SettingModel
{     
     #[ORM\Id]
     #[ORM\GeneratedValue]
     #[ORM\Column(type: "integer")]
    protected int $id;
}
  1. Update your doctrine schema., (*26)

  2. Register settings provider:, (*27)

Helis\SettingsManagerBundle\Provider\DoctrineOrmSettingsProvider:
    arguments:
        $entityManager: '@doctrine.orm.default_entity_manager'
        $settingsEntityClass: 'App\Entity\Setting'
    tags:
        - { name: settings_manager.provider, provider: orm, priority: 20 }

Helis\SettingsManagerBundle\Provider\PasetoCookieSettingsProvider, (*28)

This is a provider, which only enables existing settings by using a cookie. Cookies are encoded, so that they could not be randomly enabled by users., (*29)

Required libraries:, (*30)

  • paragonie/paseto, (*31)

    composer require paragonie/paseto, (*32)

    Paseto is used to encrypt cookies., (*33)

    Configuration example:, (*34)

Helis\SettingsManagerBundle\Provider\PasetoCookieSettingsProvider:
    arguments:
        $serializer: '@settings_manager.serializer'
    tags:
        - { name: settings_manager.provider, provider: cookie, priority: 30 }
        - { name: kernel.event_subscriber }

Helis\SettingsManagerBundle\Provider\AsymmetricPasetoCookieSettingsProvider, (*35)

This is a provider, which only enables existing settings by using a cookie. Cookies are encoded with asymmetric private and public keys, so that they could not be randomly enabled by users., (*36)

Required libraries:, (*37)

  • paragonie/paseto, (*38)

    composer require paragonie/paseto, (*39)

    Paseto is used to encrypt cookies., (*40)

    Configuration example:, (*41)

Helis\SettingsManagerBundle\Provider\AsymmetricPasetoCookieSettingsProvider:
    arguments:
        $serializer: '@settings_manager.serializer'
    tags:
        - { name: settings_manager.provider, provider: asymmetric_cookie, priority: 40 }
        - { name: kernel.event_subscriber }

Helis\SettingsManagerBundle\Provider\JwtCookieSettingsProvider, (*42)

This is a provider, which only enables existing settings by using a cookie. Cookies are encoded with asymmetric private and public keys, so that they could not be randomly enabled by users., (*43)

Required libraries:, (*44)

  • lcobucci/jwt, (*45)

    composer require lcobucci/jwt, (*46)

    JWT is used to encrypt cookies., (*47)

    Configuration example:, (*48)

Helis\SettingsManagerBundle\Provider\JwtCookieSettingsProvider:
    arguments:
        $serializer: '@settings_manager.serializer'
        $publicKey: 'file://%kernel.project_dir%/config/keys/settings_cookie_public.key'
        $privateKey: 'file://%kernel.project_dir%/config/keys/settings_cookie_private.key'
    tags:
        - { name: settings_manager.provider, provider: jwt_cookie, priority: 50 }
        - { name: kernel.event_subscriber }

AWS SSM settings provider

Helis\SettingsManagerBundle\Provider\AwsSsmSettingsProvider, (*49)

This is a provider, which is used only for reading and updating existing ssm parameters as settings., (*50)

Required libraries:, (*51)

Configuration example:, (*54)

Helis\SettingsManagerBundle\Provider\AwsSsmSettingsProvider:
    arguments:
        - '@Aws\Ssm\SsmClient'
        - '@settings_manager.serializer'
        - ['amazing_parameter_name']
    tags:
        - { name: settings_manager.provider, provider: aws_ssm }

Phpredis decorating settings provider

Helis\SettingsManagerBundle\Provider\DecoratingRedisSettingsProvider, (*55)

This provider is used to cache other settings providers like DoctrineORM or AWS SSM. It uses Redis client, not doctrine/cache providers or symfony/cache adapters because we want to take advantage of redis data structures for simplier invalidation process., (*56)

Required extensions:, (*57)

  • phpredis, (*58)

    pecl install redis-5.3.7, (*59)

Configuration example:, (*60)

Helis\SettingsManagerBundle\Provider\DecoratingRedisSettingsProvider:
    decorates: 'Helis\SettingsManagerBundle\Provider\DoctrineOrmSettingsProvider'
    arguments:
        $decoratingProvider: 'Helis\SettingsManagerBundle\Provider\DecoratingRedisSettingsProvider.inner'
        $redis: '@settings.cache.redis' # you need to register your own \Redis client in container
        $serializer: '@settings_manager.serializer'

Predis decorating settings provider

Helis\SettingsManagerBundle\Provider\DecoratingPredisSettingsProvider, (*61)

Same as phpredis decorating settings provider It just replaces the phpredis extension with predis., (*62)

Required libraries:, (*63)

Cache decorating provider

Helis\SettingsManagerBundle\Provider\DecoratingCacheSettingsProvider, (*66)

This provider is used to cache other settings providers that implements ModificationAwareSettingsProviderInterface. At the moment supports phpredis decorating settings provider and predis decorating settings provider. It uses Symfony PHP Files Cache Adapter. Single change in decorating provider causes whole cache to be invalidated. Supports symfony cache component adapters, (*67)

Required libraries and extensions:, (*68)

composer require symfony/cache symfony/lock, (*69)

Configuration example:, (*70)

settings_manager.decorating_provider.cache:
    class: 'Helis\SettingsManagerBundle\Provider\DecoratingCacheSettingsProvider'
    decorates: 'Helis\SettingsManagerBundle\Provider\DecoratingRedisSettingsProvider'
    arguments:
        $decoratingProvider: '@settings_manager.decorating_provider.cache.inner'
        $serializer: '@settings_manager.serializer'
        $cache: '@cache.settings'
        $lockFactory: '@symfony_flock_factory'

Settings provider mock

This is a special provider supposed to be used in tests only. Useful, when there is a need to mock mustGet... calls., (*71)

Configuration example:, (*72)

    settings_manager.provider.mock:
        class: Helis\SettingsManagerBundle\Test\Provider\SettingsProviderMock
        tags:
            - { name: settings_manager.provider, provider: mock, priority: 9999 }

Mocking:, (*73)

    ...

    use SettingsIntegrationTrait;

    protected function setUp()
    {
        parent::setUp();

        SettingsProviderMock::addSetting(
            (new SettingModel())
                ->setName('awesome_setting')
                ->setDomain(
                    (new DomainModel())
                        ->setName('some_domain')
                        ->setEnabled(true)
                )
        );
    }

    ...

Configuration reference

helis_settings_manager:
    settings:
        -
            name: foo
            description: 'foo desc'
            domain: default # Used for grouping settings.
            type: bool
            data: false
            tags: [super_switch]
    settings_router:
        treat_as_default_providers: ['config']
    profiler:
        enabled: false
    logger:
        enabled: false
        service_id: null # Psr\Log\LoggerInterface service id
    settings_files:
        # - '%kernel.root_dir%/config/extra_settings.yml'

User interface

User interface can be used to change setting values, enable or disable domains., (*74)

  1. Bundled user interface requires knp-menu-bundle, jsrouting-bundle., (*75)

    composer require symfony/form symfony/validator symfony/translation symfony/twig-bundle symfony/asset knplabs/knp-menu-bundle friendsofsymfony/jsrouting-bundle, (*76)

  2. Include routing file., (*77)

# <=Symfony3, app/config/routing.yml 
# >=Symfony4, config/routes/settings_manager.yaml

settings_manager:
    resource: '@HelisSettingsManagerBundle/Resources/config/routing.yaml'
    prefix: /settings

That's it. Now go to the /settings path and you will see the settings user interface., (*78)

Twig

The Twig extension is also added to get settings in your twig templates. Just like in SettingsRouter, first argument is the setting name and the second sets default value., (*79)

{{ setting_get('foo', false) }}

Controller

Helis\SettingsManagerBundle\Controller\Traits\SettingsControllerTrait, (*80)

Adds a method to deny access, unless a setting is enabled. It's using SettingsRouter, which, again, will be injected by autowire., (*81)

public function indexAction(): Response
{
    $this->denyUnlessEnabled('index_page');
    ...
}

Contribution

New feature branches should be created from the master branch., (*82)

The Versions