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

Database Config Bundle Laravel Package

carlinhus/database-config-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require carlinhus/database-config-bundle:dev-master
    

    Update AppKernel.php to include the bundle and extend getContainerBuilder():

    public function registerBundles() {
        return [
            new Carlinhus\DatabaseConfigBundle\CarlinhusDatabaseConfigBundle(),
            // ...
        ];
    }
    
    protected function getContainerBuilder() {
        return new \Carlinhus\DatabaseConfigBundle\DependencyInjection\Compiler\ContainerBuilder(
            new \Symfony\Component\DependencyInjection\ParameterBag\ParameterBag($this->getKernelParameters())
        );
    }
    
  2. Run migrations:

    php bin/console doctrine:schema:update --force
    
  3. First use case: Define a config entry in the database via a custom CLI command or admin panel:

    INSERT INTO database_config (name, value, bundle) VALUES ('app.some_param', 'dynamic_value', 'app');
    

    Access it in a service:

    $value = $this->container->getParameter('app.some_param');
    

Where to Look First

  • Database table: database_config (check src/Carlinhus/DatabaseConfigBundle/Resources/doc/schema.sql).
  • Configuration precedence: Database values override config.yml/parameters.yml.
  • Cache: All configs are cached (no direct DB hits after first load).

Implementation Patterns

Core Workflows

  1. Dynamic Configuration Management:

    • Use for environment-specific settings (e.g., API keys, feature flags) without redeploying.
    • Example: Store app.debug or monolog.level in the DB for runtime toggling.
  2. Admin Panel Integration:

    • Build a CRUD interface (e.g., with EasyAdmin) to manage database_config entries.
    • Example route:
      // src/AppBundle/Controller/ConfigController.php
      public function updateConfig(Request $request, EntityManager $em) {
          $config = $em->getRepository(Config::class)->find($request->get('id'));
          $config->setValue($request->get('value'));
          $em->flush();
          // Clear cache to reflect changes (see "Gotchas").
      }
      
  3. Bundle-Specific Configs:

    • Scope configs by bundle (e.g., fos_user.password_min_length).
    • Query configs for a specific bundle:
      $configs = $em->createQuery('SELECT c FROM AppBundle:DatabaseConfig c WHERE c.bundle = :bundle')
          ->setParameter('bundle', 'fos_user')
          ->getResult();
      
  4. Validation Layer:

    • Add validation in a pre-update event listener (e.g., reject non-serializable values):
      // src/AppBundle/EventListener/ConfigListener.php
      public function preUpdate(Config $config) {
          if (!is_scalar($config->getValue()) && !is_array($config->getValue())) {
              throw new \InvalidArgumentException('Value must be scalar or array');
          }
      }
      

Integration Tips

  • Cache Invalidation: Use Symfony’s cache system to invalidate configs after updates:
    $this->container->get('carlinhus_database_config.cache_clearer')->clear();
    
  • Environment Isolation: Filter configs by environment (e.g., dev/prod) via a custom query or bundle column.
  • Default Fallbacks: Combine with Symfony’s %parameter% syntax for defaults:
    # config.yml
    app.some_param: "%app.some_param_default%"
    
    Override in DB with app.some_param.

Gotchas and Tips

Pitfalls

  1. Cache Stale Data:

    • Issue: Changes to database_config aren’t reflected until cache is cleared.
    • Fix: Call $container->get('carlinhus_database_config.cache_clearer')->clear() after updates.
    • Alternative: Use CacheWarmer to auto-clear on config changes (see Symfony CacheWarmer).
  2. Bundle Name Collisions:

    • Issue: Configs with duplicate name + bundle pairs will overwrite each other.
    • Fix: Use unique names (e.g., app.feature_x.enabled instead of feature.enabled).
  3. Non-Scalar Values:

    • Issue: The bundle expects value to be serializable (e.g., no objects).
    • Fix: Store complex data as JSON strings and decode manually:
      $raw = $config->getValue(); // '{"key":"value"}'
      $data = json_decode($raw, true);
      
  4. Doctrine ORM Conflicts:

    • Issue: If using Doctrine, ensure the database_config table isn’t managed by another bundle.
    • Fix: Explicitly map the entity in config.yml:
      doctrine:
          orm:
              mappings:
                  carlinhus_database_config:
                      type: yaml
                      dir: "%kernel.root_dir%/config/doctrine"
                      prefix: Carlinhus\DatabaseConfigBundle\Entity
                      alias: DatabaseConfig
      

Debugging Tips

  • Check Cached Values: Dump the container’s parameter bag to verify DB configs are loaded:
    dump($this->container->getParameterBag()->all());
    
  • SQL Queries: Enable Doctrine debug mode to inspect queries:
    # config.yml
    doctrine:
        dbal:
            logging: true
    
  • Bundle Logs: Enable debug logging for the bundle:
    # config.yml
    carlinhus_database_config:
        debug: true
    

Extension Points

  1. Custom Config Sources:

    • Extend the ConfigLoader to support additional sources (e.g., Redis):
      class RedisConfigLoader extends \Carlinhus\DatabaseConfigBundle\Loader\ConfigLoader {
          public function load() {
              $redis = $this->container->get('redis');
              return $redis->hGetAll('config:app');
          }
      }
      
    • Register as a service with the carlinhus_database_config.loader tag.
  2. Event Dispatching:

    • Listen for carlinhus.database_config.pre_load and post_load events to modify configs:
      // src/AppBundle/EventListener/ConfigEventListener.php
      public function onPreLoad(ConfigLoadEvent $event) {
          $event->setConfig('app.timeout', 30); // Override dynamically
      }
      
    • Bind in services.yml:
      services:
          app.config_listener:
              class: AppBundle\EventListener\ConfigEventListener
              tags:
                  - { name: kernel.event_listener, event: carlinhus.database_config.pre_load }
      
  3. Custom Validation:

    • Override the ConfigValidator to enforce rules (e.g., regex for emails):
      class CustomConfigValidator extends \Carlinhus\DatabaseConfigBundle\Validator\ConfigValidator {
          public function validate($value, $config) {
              if ($config->getName() === 'app.email' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
                  throw new \InvalidArgumentException('Invalid email');
              }
          }
      }
      
    • Configure in config.yml:
      carlinhus_database_config:
          validator: app.custom_config_validator
      
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.
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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