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

certunlp/database-config-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

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

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

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

    php bin/console doctrine:schema:update --force
    
  3. First use case: Define a config in config.yml (e.g., my_config: true) and override it via the database by inserting a record into the unifik_database_config table:

    INSERT INTO unifik_database_config (name, value, type)
    VALUES ('my_config', 'false', 'parameter');
    

Implementation Patterns

Workflows

  1. Dynamic Configuration Management:

    • Store Symfony parameters/configs in the database (e.g., API keys, feature flags, or environment-specific settings).
    • Override static config.yml/parameters.yml values without redeploying.
    • Example: Toggle a feature flag dynamically:
      # config.yml
      features:
        experimental_ui: false
      
      -- Override via DB
      INSERT INTO unifik_database_config (name, value, type)
      VALUES ('features.experimental_ui', 'true', 'parameter');
      
  2. Environment-Specific Configs:

    • Use the same codebase across environments (dev/staging/prod) by loading configs from the database.
    • Example: Database URLs per environment:
      INSERT INTO unifik_database_config (name, value, type)
      VALUES ('database_url', 'mysql://user:pass@prod-db:3306/app', 'parameter');
      
  3. Admin Panel Integration:

    • Build a CRUD interface (e.g., with EasyAdmin or SonataAdmin) to let non-developers manage configs.
    • Example: Admin controller to update configs:
      // src/Controller/ConfigController.php
      public function update(Config $config, Request $request)
      {
          $config->setValue($request->request->get('value'));
          $entityManager->flush();
          return new Response('Config updated!');
      }
      

Integration Tips

  • Caching: Configs are cached by Symfony’s container. Clear cache after DB updates:
    php bin/console cache:clear
    
  • Validation: Add validation logic in a custom service to sanitize DB-loaded configs:
    // src/Service/ConfigValidator.php
    public function validate(array $configs): array
    {
        return array_filter($configs, fn($value) => !empty($value));
    }
    
  • Events: Listen to kernel.request to reload configs if needed (e.g., for real-time updates):
    // src/EventListener/ConfigReloadListener.php
    public function onKernelRequest(GetResponseEvent $event)
    {
        if ($event->isMasterRequest() && $this->configService->isDirty()) {
            $this->configService->reload();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Cache Invalidation:

    • Forgetting to clear the cache after DB updates will result in stale configs.
    • Fix: Automate cache clearing post-DB update (e.g., via a post-save Doctrine event).
  2. Naming Conflicts:

    • Overwriting Symfony’s core parameters (e.g., kernel.debug) can break the app.
    • Fix: Prefix custom configs (e.g., app.my_config) and avoid core keys.
  3. Type Mismatches:

    • The DB stores values as strings. Ensure proper casting in your code:
      $debugMode = (bool) $this->container->getParameter('kernel.debug');
      
  4. Schema Updates:

    • Running doctrine:schema:update --force without backups risks data loss.
    • Fix: Use migrations (doctrine:migrations:execute) for safer schema changes.

Debugging

  • Check DB Values: Query the unifik_database_config table to verify configs:
    SELECT * FROM unifik_database_config WHERE name LIKE '%my_config%';
    
  • Symfony Debug Toolbar: Use the "Config" panel to inspect loaded parameters/configs and spot overrides.

Extension Points

  1. Custom Config Sources: Extend the bundle to load configs from other sources (e.g., Redis):

    // src/DependencyInjection/Compiler/ExtendedContainerBuilder.php
    class ExtendedContainerBuilder extends ContainerBuilder
    {
        public function __construct(ParameterBag $parameterBag, array $extraSources = [])
        {
            $this->extraSources = $extraSources;
        }
    }
    
  2. Access Control: Add middleware to restrict config updates to admin users:

    // src/EventListener/SecureConfigListener.php
    public function onKernelRequest(GetResponseEvent $event)
    {
        if ($event->getRequest()->isXmlHttpRequest() &&
            !$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException();
        }
    }
    
  3. Config Versioning: Track changes to configs using Doctrine lifecycle callbacks:

    // src/Entity/Config.php
    public function preUpdate()
    {
        $this->setUpdatedAt(new \DateTime());
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware