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

Setting Bundle Laravel Package

awaresoft/setting-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require awaresoft/setting-bundle
    

    Note: Due to symlinking requirements, follow the README for local development.

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        Awaresoft\SettingBundle\AwaresoftSettingBundle::class => ['all' => true],
    ];
    
  3. Database Setup: Run migrations (if using Doctrine):

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  4. First Use Case: Define a setting in config/packages/awaresoft_setting.yaml:

    awaresoft_setting:
        settings:
            app:
                name: "My App"
                debug: false
    

    Access it in a controller:

    use Awaresoft\SettingBundle\Setting\SettingManager;
    
    class MyController extends AbstractController
    {
        public function index(SettingManager $settingManager)
        {
            $appName = $settingManager->get('app.name');
            return new Response($appName);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Configuration Management:

    • Use the bundle to manage dynamic app settings (e.g., API keys, feature flags) without redeploying.
    • Example: Toggle a feature flag:
      awaresoft_setting:
          settings:
              features:
                  new_ui: true
      
      $isNewUIEnabled = $settingManager->get('features.new_ui');
      
  2. Sonata Admin Integration:

    • Expose settings in the Sonata Admin panel for non-developers:
      sonata_admin:
          options:
              models:
                  Awaresoft\SettingBundle\Entity\Setting: ~
      
    • Create a custom admin class to filter/group settings:
      use Awaresoft\SettingBundle\Entity\Setting;
      use Sonata\AdminBundle\Admin\AbstractAdmin;
      
      class SettingAdmin extends AbstractAdmin
      {
          protected function configureListFields(ListMapper $listMapper)
          {
              $listMapper
                  ->add('name')
                  ->add('value')
                  ->add('group', null, ['label' => 'Category']);
          }
      }
      
  3. Environment-Specific Settings:

    • Override settings per environment (e.g., config/packages/dev/awaresoft_setting.yaml):
      awaresoft_setting:
          settings:
              app:
                  debug: true
      
  4. Validation:

    • Validate settings via constraints (e.g., in a custom setter):
      use Symfony\Component\Validator\Constraints as Assert;
      
      $settingManager->set('app.max_users', 100, [
          new Assert\Type(['type' => 'integer']),
          new Assert\GreaterThan(0),
      ]);
      
  5. Caching:

    • Cache settings globally (enabled by default). Clear cache when settings change:
      php bin/console cache:clear
      

Integration Tips

  • Event Listeners: Listen for setting changes to trigger actions (e.g., log changes or restart services):

    use Awaresoft\SettingBundle\Event\SettingUpdatedEvent;
    use Symfony\Component\EventDispatcher\GenericEvent;
    
    $dispatcher->addListener(SettingUpdatedEvent::NAME, function (SettingUpdatedEvent $event) {
        // Log or react to changes
    });
    
  • Dependency Injection: Inject SettingManager into services for reusable setting access:

    class MyService
    {
        public function __construct(private SettingManager $settingManager) {}
    
        public function getConfig()
        {
            return [
                'debug' => $this->settingManager->get('app.debug'),
            ];
        }
    }
    
  • Fixtures: Load default settings via Doctrine fixtures:

    use Awaresoft\SettingBundle\Entity\Setting;
    use Doctrine\Common\DataFixtures\FixtureInterface;
    
    class LoadSettings implements FixtureInterface
    {
        public function load(ObjectManager $manager)
        {
            $setting = new Setting();
            $setting->setName('app.name');
            $setting->setValue('My App');
            $setting->setGroup('app');
            $manager->persist($setting);
            $manager->flush();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Symlinking Requirements:

    • The bundle expects symlinking to /src/Awaresoft. If using Composer, remove the package from /vendor and update autoload_psr4.php manually (as per README).
    • Workaround: Use composer install --prefer-source for local development.
  2. Caching Issues:

    • Settings are cached by default. Clear cache after manual DB changes:
      php bin/console cache:clear
      
    • Disable caching in config/packages/awaresoft_setting.yaml:
      awaresoft_setting:
          cache_enabled: false
      
  3. Sonata Admin Conflicts:

    • Ensure the Setting entity is not overridden by other bundles (e.g., sonata-project/core-bundle). Explicitly map the admin class:
      sonata_admin:
          options:
              models:
                  Awaresoft\SettingBundle\Entity\Setting:
                      label: Settings
                      admin_service: awaresoft_setting.admin.setting
      
  4. Backward Compatibility:

    • Avoid breaking changes (e.g., renaming setting keys). Use migration scripts to update values:
      // Example: Rename 'old.key' to 'new.key'
      $oldValue = $settingManager->get('old.key');
      $settingManager->set('new.key', $oldValue);
      $settingManager->delete('old.key');
      
  5. Serialization:

    • Settings are stored as strings. Use JSON for complex values:
      $settingManager->set('app.config', json_encode(['key' => 'value']));
      $config = json_decode($settingManager->get('app.config'), true);
      

Debugging Tips

  1. Check DB Directly: Query the setting table to verify values:

    SELECT * FROM setting WHERE name LIKE 'app.%';
    
  2. Enable Debug Mode: Temporarily disable caching to see real-time changes:

    awaresoft_setting:
        cache_enabled: false
    
  3. Event Debugging: Listen for events to trace changes:

    $dispatcher->addListener(SettingUpdatedEvent::NAME, function (SettingUpdatedEvent $event) {
        error_log('Setting updated: ' . $event->getSetting()->getName());
    });
    
  4. Validation Errors: Check for constraint violations when setting values:

    try {
        $settingManager->set('invalid.key', 'value');
    } catch (ConstraintViolationException $e) {
        // Handle validation errors
    }
    

Extension Points

  1. Custom Setting Types: Extend the Setting entity to add metadata (e.g., description, type):

    namespace Awaresoft\SettingBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class Setting
    {
        // ...
        #[ORM\Column(type: 'string', nullable: true)]
        private ?string $description = null;
    
        #[ORM\Column(type: 'string', nullable: true)]
        private ?string $type = 'string'; // e.g., 'string', 'integer', 'boolean'
    }
    
  2. Custom Storage: Override the storage layer to use Redis or another backend:

    use Awaresoft\SettingBundle\Storage\SettingStorageInterface;
    
    class RedisSettingStorage implements SettingStorageInterface
    {
        public function get(string $name): ?string
        {
            return Redis::get($name);
        }
    
        public function set(string $name, string $value): void
        {
            Redis::set($name, $value);
        }
    
        // Implement other methods...
    }
    

    Register the service in config/services.yaml:

    services:
        Awaresoft\SettingBundle\Storage\SettingStorageInterface: '@redis_setting_storage'
    
  3. Custom Groups: Add a Group entity to categorize settings hierarchically:

    #[ORM\Entity]
    class Group
    {
        #[ORM\Id]
        #[ORM\GeneratedValue]
        #[ORM\Column(type: 'integer')]
        private ?int $id = null;
    
        #[ORM\Column(type: 'string')]
        private string $name;
    
        #[ORM\OneToMany(mappedBy: 'group', targetEntity: Setting::class)]
        private Collection $settings;
    }
    

    Update the Setting entity to reference the group:

    #[ORM\ManyToOne(targetEntity: Group::class, inversedBy: 'settings')
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity