PHP code example of ecourty / platform-parameter-bundle

1. Go to this page and download the library: Download ecourty/platform-parameter-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ecourty / platform-parameter-bundle example snippets


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

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', [], ',');
    }
}

// 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

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

$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')!

use Ecourty\PlatformParameterBundle\Event\PlatformParameterCreatedEvent;
use Ecourty\PlatformParameterBundle\Event\PlatformParameterUpdatedEvent;
use Ecourty\PlatformParameterBundle\Event\PlatformParameterDeletedEvent;

// src/EventSubscriber/ParameterChangeSubscriber.php
namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Ecourty\PlatformParameterBundle\Event\PlatformParameterUpdatedEvent;

class ParameterChangeSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private NotificationService $notifier,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            PlatformParameterUpdatedEvent::class => 'onParameterUpdated',
        ];
    }

    public function onParameterUpdated(PlatformParameterUpdatedEvent $event): void
    {
        $parameter = $event->getParameter();
        
        // Send notification for critical parameters
        if ($parameter->getKey() === 'maintenance_mode') {
            $this->notifier->send(sprintf(
                'Maintenance mode changed from "%s" to "%s"',
                $event->getOldValue(),
                $event->getNewValue()
            ));
        }
    }
}

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

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

use Ecourty\PlatformParameterBundle\Contract\PlatformParameterWriterInterface;

class MyService
{
    public function __construct(
        private readonly PlatformParameterWriterInterface $parameterWriter
    ) {
    }

    public function updateConfiguration(): void
    {
        // Update parameters with type-safe methods
        $this->parameterWriter->setString('site_name', 'New Site Name');
        $this->parameterWriter->setInt('max_uploads', 100);
        $this->parameterWriter->setBool('maintenance_mode', true);
        $this->parameterWriter->setJson('api_config', ['timeout' => 60]);
        $this->parameterWriter->setList('allowed_ips', ['192.168.1.1', '10.0.0.1']);
        $this->parameterWriter->setFloat('tax_rate', 19.5);
        $this->parameterWriter->setDateTime('last_sync', new \DateTimeImmutable());
        
        // Delete a parameter
        $this->parameterWriter->delete('old_parameter');
    }
}

setString(string $key, string $value): void
setInt(string $key, int $value): void
setBool(string $key, bool $value): void
setJson(string $key, array $value): void
setList(string $key, array $value, string $separator = "\n"): void
setFloat(string $key, float $value): void
setDateTime(string $key, \DateTimeImmutable $value, ?string $format = null): void
delete(string $key): void

use Ecourty\PlatformParameterBundle\Entity\PlatformParameter;
use Ecourty\PlatformParameterBundle\Enum\ParameterType;
use Doctrine\ORM\EntityManagerInterface;

class ParameterSeeder
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager
    ) {
    }

    public function createParameter(): void
    {
        $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');

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

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');

// 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);
}

// 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');
    }
}

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

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

use Doctrine\ORM\Mapping as ORM;
use Ecourty\PlatformParameterBundle\Model\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;
    }
}

// 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")');
    }
}
bash
# Create a migration
php bin/console doctrine:migrations:diff

# Apply the migration
php bin/console doctrine:migrations:migrate
bash
php bin/console platform-parameter:list
bash
# Update an existing parameter
php bin/console platform-parameter:set max_uploads 50
php bin/console platform-parameter:set site_name "New Site Name"
php bin/console platform-parameter:set maintenance_mode true
bash
# Delete with confirmation prompt
php bin/console platform-parameter:delete old_param

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