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

dmishh/settings-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require rvanlaak/settings-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Rvanlaak\SettingsBundle\RvanlaakSettingsBundle::class => ['all' => true],
    ];
    
  2. Database Migration: Run the bundle’s migration to create the settings table:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Use Case: Inject SettingsManager in a controller/service:

    use Rvanlaak\SettingsBundle\Manager\SettingsManagerInterface;
    
    public function __construct(private SettingsManagerInterface $settingsManager) {}
    
    public function configureSettings()
    {
        $this->settingsManager->set('site_name', 'MyApp');
        $globalName = $this->settingsManager->get('site_name'); // 'MyApp'
    }
    
  4. Twig Integration: Use the get_setting() function in templates:

    <h1>{{ get_setting('site_name') }}</h1>
    

Implementation Patterns

Core Workflows

  1. Global vs. User-Specific Settings:

    • Global: Use set('key', 'value')/get('key') for app-wide settings.
    • User-Specific: Pass a User object as the second argument:
      $this->settingsManager->set('theme', 'dark', $user);
      $userTheme = $this->settingsManager->get('theme', $user);
      
  2. Validation with Forms: Define a form type for settings validation:

    use Rvanlaak\SettingsBundle\Form\SettingsType;
    
    $form = $this->createForm(SettingsType::class, $settingsData);
    if ($form->isSubmitted() && $form->isValid()) {
        $this->settingsManager->setMultiple($form->getData());
    }
    
  3. Serialization:

    • Default: PHP serialize() (compact, fast).
    • JSON: Configure in config/packages/rvanlaak_settings.yaml:
      rvanlaak_settings:
          serialization: json
      
  4. Caching: Enable PSR-6 cache (e.g., Symfony Cache) for performance:

    rvanlaak_settings:
        cache: cache.app
    
  5. Scopes: Use custom scopes (e.g., role, tenant) by extending the Scope class:

    $this->settingsManager->set('max_uploads', 10, ['scope' => 'admin']);
    $this->settingsManager->get('max_uploads', null, ['scope' => 'admin']);
    

Integration Tips

  1. Event Listeners: Listen to settings.update or settings.delete events for side effects:

    use Rvanlaak\SettingsBundle\Event\SettingsEvent;
    
    public function onSettingsUpdate(SettingsEvent $event) {
        // Log or notify when settings change
    }
    
  2. Dependency Injection: Prefer constructor injection over service locator:

    public function __construct(
        private SettingsManagerInterface $settingsManager,
        private SettingsRepositoryInterface $settingsRepository
    ) {}
    
  3. Testing: Use the SettingsManager mock in tests:

    $mockSettings = $this->createMock(SettingsManagerInterface::class);
    $mockSettings->method('get')->willReturn('test_value');
    
  4. CLI Management: Create a custom command to bulk-update settings:

    use Rvanlaak\SettingsBundle\Manager\SettingsManagerInterface;
    
    class UpdateSettingsCommand extends Command {
        protected function execute(InputInterface $input, OutputInterface $output) {
            $this->settingsManager->setMultiple([
                'key1' => 'value1',
                'key2' => 'value2',
            ]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Serialization Conflicts:

    • JSON serialization may fail for complex objects (e.g., closures, resources). Stick to serialize for non-PHP-standard types.
    • Fix: Implement a custom serializer by extending Rvanlaak\SettingsBundle\Serializer\SerializerInterface.
  2. Cache Invalidation:

    • Changes to settings won’t reflect in cached views until the cache is cleared.
    • Fix: Use cache:clear or manually invalidate the cache tag:
      $this->settingsManager->set('key', 'value', [], ['cache_tag' => 'settings']);
      
  3. Scope Ambiguity:

    • Overlapping scopes (e.g., user + role) may lead to unexpected precedence.
    • Fix: Document scope priority rules or use explicit scope names:
      $this->settingsManager->get('key', $user, ['scope' => 'user:premium']);
      
  4. Doctrine Events:

    • The bundle triggers prePersist, preUpdate, and preRemove events. Avoid infinite loops by not modifying settings in these events.
  5. Legacy dmissh/settings-bundle:

    • The package was renamed; ensure your composer.json and autoloader reflect rvanlaak/settings-bundle.

Debugging

  1. Query Logging: Enable Doctrine debug mode to inspect SQL queries:

    doctrine:
        dbal:
            logging: true
            profiling: true
    
  2. Setting Existence: Check if a setting exists before fetching:

    if ($this->settingsManager->has('key')) {
        $value = $this->settingsManager->get('key');
    }
    
  3. Serialization Errors: Wrap JSON serialization in a try-catch:

    try {
        $this->settingsManager->set('data', $complexObject, null, [], 'json');
    } catch (\RuntimeException $e) {
        // Fallback to serialize or log the error
    }
    

Extension Points

  1. Custom Serializers: Implement Rvanlaak\SettingsBundle\Serializer\SerializerInterface for custom formats (e.g., YAML):

    use Rvanlaak\SettingsBundle\Serializer\SerializerInterface;
    
    class YamlSerializer implements SerializerInterface {
        public function serialize($data) { /* ... */ }
        public function unserialize($data) { /* ... */ }
    }
    

    Register in services.yaml:

    rvanlaak_settings.serializer.yaml:
        class: App\Serializer\YamlSerializer
        tags: ['rvanlaak_settings.serializer']
    
  2. Custom Scopes: Extend Rvanlaak\SettingsBundle\Model\Scope for multi-level scopes (e.g., tenant:user):

    class TenantScope extends Scope {
        public function getKey(): string {
            return 'tenant:' . $this->getValue();
        }
    }
    
  3. Validation Rules: Add custom constraints to SettingsType:

    use Symfony\Component\Validator\Constraints as Assert;
    
    $builder->add('key', Assert\Type(['type' => 'string', 'message' => 'Must be a string']));
    
  4. Event Subscribers: Subscribe to SettingsEvents for real-time updates:

    use Rvanlaak\SettingsBundle\Event\SettingsEvents;
    
    public static function getSubscribedEvents() {
        return [
            SettingsEvents::SETTINGS_UPDATE => 'onSettingsUpdate',
        ];
    }
    

Configuration Quirks

  1. Default Serialization: The default (serialize) may not work for objects with circular references. Use JSON for such cases.

  2. Cache TTL: Configure cache lifetime in rvanlaak_settings.yaml:

    rvanlaak_settings:
        cache_ttl: 3600  # 1 hour
    
  3. Environment-Specific Settings: Use Symfony’s parameter bag to override settings per environment:

    # config/packages/dev/rvanlaak_settings.yaml
    rvanlaak_settings:
        default_values:
            debug_mode: true
    
  4. Doctrine Entity Manager: Ensure the bundle uses the same EM as your app. Configure in config/packages/rvanlaak_settings.yaml:

    rvanlaak_settings:
        entity_manager: default  # or 'custom_em'
    
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
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