Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Settings Bundle Laravel Package

cpoint-eu/settings-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cpoint-eu/settings-bundle
    

    Enable the bundle in config/bundles.php:

    CreativePoint\SettingsBundle\CreativePointSettingsBundle::class => ['all' => true],
    
  2. First Use Case:

    • Run migrations to create the Setting entity table:
      php bin/console doctrine:migrations:diff
      php bin/console doctrine:migrations:migrate
      
    • Define a DTO (Data Transfer Object) for your settings. Example:
      // src/DTO/AppSettings.php
      namespace App\DTO;
      
      class AppSettings
      {
          public string $siteName;
          public bool $maintenanceMode;
      }
      
    • Register the DTO in the bundle configuration (config/packages/creative_point_settings.yaml):
      creative_point_settings:
        objects:
          App\DTO\AppSettings: ~
      
  3. Accessing Settings: Inject the SettingsProvider service into your controller or service:

    use CreativePoint\SettingsBundle\Provider\SettingsProviderInterface;
    
    class SomeController
    {
        public function __construct(private SettingsProviderInterface $settingsProvider) {}
    
        public function index()
        {
            $settings = $this->settingsProvider->get('App\DTO\AppSettings');
            // Use $settings->siteName, $settings->maintenanceMode
        }
    }
    

Implementation Patterns

Workflows

  1. Defining Settings:

    • Create a DTO for each group of related settings (e.g., AppSettings, EmailSettings).
    • Populate the Setting table via a form, admin panel, or CLI command. Example:
      php bin/console doctrine:fixtures:load --append
      
      (Create a fixture to seed initial settings.)
  2. Caching Strategy:

    • The bundle caches settings by default (TTL configurable in cache_ttl). Override the cache key in config if needed:
      creative_point_settings:
        cache_key: 'app_settings_%s'
      
    • Clear cache manually when settings are updated:
      $this->settingsProvider->clearCache('App\DTO\AppSettings');
      
  3. Validation:

    • Validate DTOs by implementing Symfony\Component\Validator\Constraint on properties or using Symfony’s validation component:
      use Symfony\Component\Validator\Constraints as Assert;
      
      class AppSettings
      {
          #[Assert\NotBlank]
          public string $siteName;
      }
      
    • Validate settings during form submission or via a command.
  4. Environment-Specific Settings:

    • Use the environment column in the Setting table to store environment-specific values (e.g., dev, prod).
    • Filter settings by environment in your DTO factory or provider:
      $settings = $this->settingsProvider->get('App\DTO\AppSettings', ['env' => 'prod']);
      
  5. Dynamic Settings Updates:

    • Use events to react to setting changes. Subscribe to the settings.update event:
      // src/EventListener/SettingsUpdateListener.php
      namespace App\EventListener;
      
      use CreativePoint\SettingsBundle\Event\SettingsEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class SettingsUpdateListener implements EventSubscriberInterface
      {
          public static function getSubscribedEvents(): array
          {
              return [
                  SettingsEvent::SETTINGS_UPDATE => 'onSettingsUpdate',
              ];
          }
      
          public function onSettingsUpdate(SettingsEvent $event)
          {
              // Log or trigger actions when settings are updated
          }
      }
      

Integration Tips

  1. Symfony Forms:

    • Create a form type to edit settings:
      // src/Form/SettingsType.php
      namespace App\Form;
      
      use App\DTO\AppSettings;
      use Symfony\Component\Form\AbstractType;
      use Symfony\Component\Form\FormBuilderInterface;
      
      class SettingsType extends AbstractType
      {
          public function buildForm(FormBuilderInterface $builder, array $options)
          {
              $builder
                  ->add('siteName')
                  ->add('maintenanceMode');
          }
      }
      
    • Use the form in a controller to update settings:
      public function editSettings(Request $request)
      {
          $settings = $this->settingsProvider->get('App\DTO\AppSettings');
          $form = $this->createForm(SettingsType::class, $settings);
          $form->handleRequest($request);
      
          if ($form->isSubmitted() && $form->isValid()) {
              $this->settingsProvider->save($settings);
              $this->addFlash('success', 'Settings updated!');
          }
      
          return $this->render('settings/edit.html.twig', ['form' => $form->createView()]);
      }
      
  2. Twig Integration:

    • Pass settings to Twig globally in a base controller or event subscriber:
      // src/EventListener/TwigSettingsListener.php
      namespace App\EventListener;
      
      use CreativePoint\SettingsBundle\Provider\SettingsProviderInterface;
      use Twig\Environment;
      
      class TwigSettingsListener
      {
          public function __construct(
              private SettingsProviderInterface $settingsProvider,
              private Environment $twig
          ) {
              $this->twig->addGlobal('app_settings', $this->settingsProvider->get('App\DTO\AppSettings'));
          }
      }
      
    • Access settings in Twig templates:
      {{ app_settings.siteName }}
      
  3. API Responses:

    • Return settings in API responses:
      public function getSettings()
      {
          return $this->json($this->settingsProvider->get('App\DTO\AppSettings'));
      }
      
  4. Testing:

    • Mock the SettingsProviderInterface in tests:
      $settingsProvider = $this->createMock(SettingsProviderInterface::class);
      $settingsProvider->method('get')->willReturn(new AppSettings());
      $this->container->set(SettingsProviderInterface::class, $settingsProvider);
      

Gotchas and Tips

Pitfalls

  1. Cache Invalidation:

    • Forgetting to clear the cache after updating settings via code (not the admin panel). Always call:
      $this->settingsProvider->clearCache('App\DTO\AppSettings');
      
    • Tip: Wrap updates in a transaction and clear cache only on success:
      $entityManager = $this->getDoctrine()->getManager();
      $entityManager->beginTransaction();
      try {
          // Update settings...
          $entityManager->flush();
          $entityManager->commit();
          $this->settingsProvider->clearCache('App\DTO\AppSettings');
      } catch (\Exception $e) {
          $entityManager->rollBack();
          throw $e;
      }
      
  2. DTO Naming Collisions:

    • Using the same DTO class name across projects or namespaces can cause conflicts. Prefix DTOs (e.g., App\DTO\AppSettings).
    • Tip: Use fully qualified class names in the bundle configuration to avoid ambiguity.
  3. Missing Default Values:

    • The bundle does not provide default values for settings. Ensure your DTOs have default values or handle null cases:
      class AppSettings
      {
          public string $siteName = 'My App'; // Default value
      }
      
  4. Performance with Large Settings:

    • Loading all settings at once can be slow. Use lazy loading or fetch only required settings:
      $this->settingsProvider->get('App\DTO\AppSettings', ['fields' => ['siteName']]);
      
    • Tip: Add an index to the Setting table for faster lookups:
      CREATE INDEX idx_setting_name ON setting(name);
      
  5. Environment Filtering:

    • The environment filter in the provider is case-sensitive. Ensure consistency when storing/retrieving settings:
      // Store
      $setting->setEnvironment('prod');
      
      // Retrieve
      $this->settingsProvider->get('App\DTO\AppSettings', ['env' => 'prod']);
      
  6. Bundle Configuration Overrides:

    • Customizing cache_key or cache_ttl requires a full config block. Partial overrides may not work as expected:
      # Correct: Full block
      creative_point_settings:
        cache_key: 'custom_%s'
        cache_ttl: 600
      

Debugging

  1. Cache Issues:

    • Check if settings are cached by inspecting the cache key:
      $cacheKey = $this->settingsProvider->getCacheKey('App\DTO\AppSettings');
      
    • Clear all cache to rule out stale entries:
      php bin/console cache:clear
      
  2. Missing Settings:

    • Verify the Setting table contains entries for your DTO. Run:
      php bin/console doctrine:query:sql "SELECT * FROM setting WHERE name LIKE '%AppSettings%'"
      
    • Ensure
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui