ecourty/platform-parameter-bundle

Symfony bundle for managing global platform parameters with type-safe access and caching

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

Type:symfony-bundle

pkg:composer/ecourty/platform-parameter-bundle

dev-main 2026-01-22 00:12 UTC

This package is auto-updated.

Last update: 2026-01-22 09:44:04 UTC


README

CI

A Symfony bundle for managing global platform parameters with type-safe access and caching.

Table of Contents

Features

  • 🎯 Type-safe parameter access - Methods for STRING, INTEGER, BOOLEAN, JSON, LIST, FLOAT, and DATETIME types
  • âš¡ PSR-6 caching - Built-in cache support for optimal performance
  • 🔧 Easy integration - Simple Symfony bundle with autowiring support
  • 📦 Doctrine ORM - Entity-based storage

Installation

composer require ecourty/platform-parameter-bundle

Optional: EasyAdmin Integration

If your project uses EasyAdmin, the bundle includes a ready-to-use CRUD controller:

composer require easycorp/easyadmin-bundle

Register the bundle

If you're not using Symfony Flex, add the bundle to config/bundles.php:

return [
    // ...
    Ecourty\PlatformParameterBundle\PlatformParameterBundle::class => ['all' => true],
];

Configuration

Create a configuration file config/packages/platform_parameter.yaml:

platform_parameter:
    entity_class: 'Ecourty\PlatformParameterBundle\Entity\PlatformParameter'  # FQCN (default)
    cache_ttl: 3600   # Cache TTL in seconds (default: 3600)
    cache_key_prefix: 'platform_parameter'  # Cache key prefix (default: 'platform_parameter')
    clear_cache_on_parameter_update: true   # Auto-clear cache on parameter changes (default: true)
    cache_adapter: null  # Cache adapter service ID (default: auto-detect, see below)

Cache Adapter Resolution

The bundle automatically creates a TagAware cache pool (platform_parameter.cache) for optimal performance out-of-the-box.

Cache adapter priority:

  1. Custom adapter (if cache_adapter is specified in config)
  2. Auto-created TagAware pool (platform_parameter.cache - created by default)
  3. Default (cache.app as ultimate fallback)

No configuration needed! The bundle works optimally by default with TagAware support.

Example - Using a custom Redis cache pool:

# config/packages/cache.yaml
framework:
    cache:
        pools:
            my_custom_cache:
                adapter: cache.adapter.redis
                default_lifetime: 7200

# config/packages/platform_parameter.yaml
platform_parameter:
    cache_adapter: 'my_custom_cache'

Example - Overriding the default pool:

# config/packages/cache.yaml
framework:
    cache:
        pools:
            platform_parameter.cache:
                adapter: cache.adapter.redis.tag_aware
                default_lifetime: 3600

# The bundle will automatically use this pool instead of creating its own

Database Setup

Run Doctrine migrations to create the platform_parameter table:

# Create a migration
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate

Usage

Basic Usage

Inject the PlatformParameterProviderInterface into your services:

use Ecourty\PlatformParameterBundle\Contract\PlatformParameterProviderInterface;

class MyService
{
    public function __construct(
        private readonly PlatformParameterProviderInterface $parameterProvider
    ) {
    }

    public function doSomething(): void
    {
        // Get a string parameter
        $siteName = $this->parameterProvider->getString('site_name');

        // Get an integer with a default value
        $maxUploads = $this->parameterProvider->getInt('max_uploads', 10);

        // Get a boolean
        $maintenanceMode = $this->parameterProvider->getBool('maintenance_mode', false);

        // Get a JSON array
        $config = $this->parameterProvider->getJson('api_config', ['timeout' => 30]);

        // Get a list (multi-line string split by newlines)
        $allowedEmails = $this->parameterProvider->getList('allowed_emails', []);

        // Get a list with custom separator (e.g., comma-separated)
        $tags = $this->parameterProvider->getList('tags', [], ',');
    }
}

Available Methods

// Get a string parameter
getString(string $key, ?string $default = null): string

// Get an integer parameter
getInt(string $key, ?int $default = null): int

// Get a boolean parameter
getBool(string $key, ?bool $default = null): bool

// Get a JSON parameter (returns array)
getJson(string $key, ?array $default = null): array

// Get a list parameter (returns string[])
getList(string $key, ?array $default = null, string $separator = "\n"): array

// Get a float parameter
getFloat(string $key, ?float $default = null): float

// Get a datetime parameter (returns DateTimeImmutable)
getDateTime(string $key, ?\DateTimeImmutable $default = null, ?string $format = null): \DateTimeImmutable

// Check if a parameter exists
has(string $key): bool

// Clear cached parameters
clearCache(?string $key = null): void  // Clear specific key or all parameters

DateTime Format Support

The getDateTime() method automatically tries these formats:

  • ISO 8601: 2026-01-21T15:30:00+00:00
  • MySQL datetime: 2026-01-21 15:30:00
  • Date only: 2026-01-21
  • French format: 21/01/2026 or 21/01/2026 15:30:00
  • Unix timestamp: 1737472200
  • Native parser: next monday, +1 week, etc.

Or specify a custom format:

$date = $parameterProvider->getDateTime('custom_date', null, 'd-m-Y');

Cache Management

The bundle automatically caches all parameters to minimize database queries. When you access a parameter (e.g., getString('site_name')), it's fetched from the database once and cached for subsequent requests. This significantly reduces database load, especially for frequently accessed parameters. The cache TTL is configurable (default: 3600 seconds / 1 hour).

Automatic Cache Clearing (Default Behavior)

By default, the bundle automatically clears the cache when you create, update, or delete a parameter:

$parameter = new PlatformParameter();
$parameter->setKey('site_name');
$parameter->setValue('My Site');
$parameter->setType(ParameterType::STRING);

$entityManager->persist($parameter);
$entityManager->flush(); // ✅ Cache is automatically cleared for 'site_name'

// No need to call $parameterProvider->clearCache('site_name')!

This is enabled by default via the clear_cache_on_parameter_update: true configuration option.

To disable automatic cache clearing:

# config/packages/platform_parameter.yaml
platform_parameter:
    clear_cache_on_parameter_update: false  # Disable auto-clear

Manual Cache Clearing

You can still manually clear the cache when needed:

// Clear specific parameter cache
$parameterProvider->clearCache('site_name');

// Clear all parameter caches (only parameters, not entire Symfony cache)
$parameterProvider->clearCache();

Note: When clearing all caches, the bundle:

  1. If using TagAwareAdapter: Uses tags for efficient invalidation
  2. Otherwise: Fetches all parameters from DB and deletes their cache items individually

Optimizing Cache Performance

The bundle automatically creates a TagAware cache pool for optimal performance. No additional configuration is needed!

Benefits:

  • ✅ Efficient bulk cache invalidation via tags
  • ✅ clearCache() without parameters is O(1) instead of O(n)
  • ✅ Works out-of-the-box without manual configuration

Advanced - Using Redis for better performance:

# config/packages/cache.yaml
framework:
    cache:
        pools:
            platform_parameter.cache:
                adapter: cache.adapter.redis.tag_aware
                default_lifetime: 3600
                provider: 'redis://localhost'

The bundle will automatically use your custom platform_parameter.cache pool if defined.

Parameter Types

The bundle supports 7 parameter types:

Type Description Example
STRING Simple text value "Hello World"
INTEGER Numeric integer 42
BOOLEAN Boolean value "true", "1", "yes"
JSON JSON object/array {"key": "value"}
LIST Multi-line or separated list "line1\nline2" or "a,b,c"
FLOAT Decimal number 19.99, -15.5, 1.5e-3
DATETIME Date/time value 2026-01-21, 2026-01-21 15:30:00

Creating Parameters

Parameters are stored as Doctrine entities. You can create them programmatically:

use Ecourty\PlatformParameterBundle\Entity\PlatformParameter;
use Ecourty\PlatformParameterBundle\Enum\ParameterType;

$parameter = new PlatformParameter();
$parameter->setKey('site_name');
$parameter->setValue('My Awesome Site');
$parameter->setType(ParameterType::STRING);
$parameter->setLabel('Site Name');
$parameter->setDescription('The name of the website');

$entityManager->persist($parameter);
$entityManager->flush();

// ✅ Cache is automatically cleared (if clear_cache_on_parameter_update is enabled, which is the default)

Error Handling

If a parameter doesn't exist and no default value is provided, a ParameterNotFoundException is thrown:

use Ecourty\PlatformParameterBundle\Exception\ParameterNotFoundException;

try {
    $value = $parameterProvider->getString('non_existent_key');
} catch (ParameterNotFoundException $e) {
    // Handle missing parameter
}

// Or use a default value to avoid exceptions
$value = $parameterProvider->getString('non_existent_key', 'default value');

CLI Commands

The bundle provides convenient console commands to manage parameters:

List all parameters

php bin/console platform-parameter:list

Displays a table with all parameters showing their key, value (truncated if too long), type, and label.

View a specific parameter

php bin/console platform-parameter:get site_name

Shows all metadata for a parameter including ID, key, value, type, label, description, and timestamps.

Create or update a parameter

# Update existing parameter (only changes the value)
php bin/console platform-parameter:set max_uploads 50

# Create new parameter (interactive mode - asks for type, label, description)
php bin/console platform-parameter:set new_param "value"

# Create new parameter (non-interactive mode)
php bin/console platform-parameter:set api_timeout 30 --type=integer --label="API Timeout" --description="Timeout in seconds" --no-interaction

Interactive mode (default):

  • If the parameter exists: updates only the value
  • If the parameter doesn't exist: prompts for type, label, and optional description

Non-interactive mode (--no-interaction):

  • Requires --type and --label options when creating a new parameter
  • --description is optional

Delete a parameter

# Delete with confirmation prompt
php bin/console platform-parameter:delete old_param

# Delete without confirmation
php bin/console platform-parameter:delete old_param --force

Shows parameter details before deletion and asks for confirmation (unless --force is used).

Clear parameter cache

# Clear cache for a specific parameter
php bin/console platform-parameter:cache:clear site_name

# Clear cache for all parameters
php bin/console platform-parameter:cache:clear

Manually clears the cache for one or all parameters. Useful if automatic cache clearing is disabled.

EasyAdmin CRUD Interface

If you have EasyAdmin installed, you can use the included CRUD controller to manage parameters.

Register the controller in your EasyAdmin dashboard:

// src/Controller/Admin/DashboardController.php
use Ecourty\PlatformParameterBundle\Controller\PlatformParameterCrudController;
use Ecourty\PlatformParameterBundle\Entity\PlatformParameter;
use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;

public function configureMenuItems(): iterable
{
    yield MenuItem::linkToDashboard('Dashboard', 'fa fa-home');
    // ...
    yield MenuItem::linkToCrud('Platform Parameters', 'fa fa-cog', PlatformParameter::class)
        ->setController(PlatformParameterCrudController::class);
}

The CRUD controller includes:

  • ✅ All CRUD operations (Create, Read, Update, Delete)
  • ✅ Field validation and help text
  • ✅ Badge colors for parameter types
  • ✅ Truncated value display in list view

Optional - Customizing the Controller:

If you need to customize the controller behavior (e.g., change titles, add custom fields, modify permissions), you can extend it:

// src/Controller/Admin/CustomPlatformParameterCrudController.php
namespace App\Controller\Admin;

use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use Ecourty\PlatformParameterBundle\Controller\PlatformParameterCrudController;

class CustomPlatformParameterCrudController extends PlatformParameterCrudController
{
    public function configureCrud(Crud $crud): Crud
    {
        return parent::configureCrud($crud)
            ->setPageTitle(Crud::PAGE_INDEX, 'My Custom Parameters');
    }
}

Then reference your custom controller in the dashboard instead:

yield MenuItem::linkToCrud('Platform Parameters', 'fa fa-cog', PlatformParameter::class)
    ->setController(CustomPlatformParameterCrudController::class);

Extending the Entity

The bundle is designed to be extensible. You can create your own entity that extends the base AbstractPlatformParameter to add custom fields.

Step 1: Create Your Custom Entity

// src/Entity/CustomPlatformParameter.php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Ecourty\PlatformParameterBundle\Entity\AbstractPlatformParameter;

#[ORM\Entity]
#[ORM\Table(name: 'platform_parameter')]
class CustomPlatformParameter extends AbstractPlatformParameter
{
    #[ORM\Column(type: 'string', length: 100, nullable: true)]
    private ?string $category = null;

    #[ORM\Column(type: 'integer', nullable: true)]
    private ?int $sortOrder = null;

    #[ORM\Column(type: 'string', length: 50, nullable: true)]
    private ?string $icon = null;

    // Getters and setters...

    public function getCategory(): ?string
    {
        return $this->category;
    }

    public function setCategory(?string $category): self
    {
        $this->category = $category;
        return $this;
    }

    public function getSortOrder(): ?int
    {
        return $this->sortOrder;
    }

    public function setSortOrder(?int $sortOrder): self
    {
        $this->sortOrder = $sortOrder;
        return $this;
    }

    public function getIcon(): ?string
    {
        return $this->icon;
    }

    public function setIcon(?string $icon): self
    {
        $this->icon = $icon;
        return $this;
    }
}

Step 2: Configure the Bundle

Update your platform_parameter.yaml configuration:

platform_parameter:
    entity_class: 'App\Entity\CustomPlatformParameter'
    cache_ttl: 3600
    cache_key_prefix: 'platform_parameter'

Step 3: Update Database Schema

# Generate migration for your custom fields
php bin/console doctrine:migrations:diff

# Run migration
php bin/console doctrine:migrations:migrate

Step 4: (Optional) Create Custom EasyAdmin CRUD Controller

If you added custom fields and want them in EasyAdmin:

// src/Controller/Admin/CustomParameterCrudController.php
namespace App\Controller\Admin;

use App\Entity\CustomPlatformParameter;
use Ecourty\PlatformParameterBundle\Controller\PlatformParameterCrudController as BaseCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;

class CustomParameterCrudController extends BaseCrudController
{
    public static function getEntityFqcn(): string
    {
        return CustomPlatformParameter::class;
    }

    public function configureFields(string $pageName): iterable
    {
        // Get base fields from parent
        yield from parent::configureFields($pageName);

        // Add your custom fields
        yield TextField::new('category', 'Category')
            ->setHelp('Parameter category for organization');

        yield IntegerField::new('sortOrder', 'Sort Order')
            ->setHelp('Display order (lower numbers first)');

        yield TextField::new('icon', 'Icon')
            ->setHelp('Icon name (e.g., "fa-cog", "bi-gear")');
    }
}

Benefits of Extending

  • ✅ Add custom metadata: category, tags, sort order, icon, etc.
  • ✅ Keep core functionality: All bundle methods work with your custom entity
  • ✅ Type-safe access: The provider continues to work seamlessly
  • ✅ No code duplication: Inherit all base fields and methods
  • ✅ EasyAdmin compatible: Custom fields integrate naturally

Development

Running Tests

composer test

Code Quality

# Run PHPStan
composer phpstan

# Fix code style
composer cs-fix

# Check code style
composer cs-check

# Run all QA checks
composer qa

License

MIT License - see LICENSE file for details.