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

Featuretoggle Bundle Laravel Package

ecn/featuretoggle-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ecn/featuretoggle-bundle twig/twig  # Include Twig if using Twig integration
    

    Add to config/bundles.php:

    return [
        // ...
        Ecn\FeatureToggleBundle\EcnFeatureToggleBundle::class => ['all' => true],
    ];
    
  2. Define Features: Create config/features.yml (add to .gitignore):

    ecn_feature_toggle:
        features:
            new_ui: false
            experimental_search: true
            dark_mode: false
    
  3. First Use Case: Check a toggle in a controller:

    use Ecn\FeatureToggleBundle\FeatureToggle;
    
    class HomeController extends AbstractController {
        public function index(FeatureToggle $toggle) {
            if ($toggle->isEnabled('new_ui')) {
                return $this->render('home/new_ui.html.twig');
            }
            return $this->render('home/default.html.twig');
        }
    }
    

Implementation Patterns

Core Workflows

  1. Runtime Toggle Management:

    • Use FeatureToggle service to check toggles dynamically:
      $toggle->isEnabled('feature_name'); // Returns bool
      $toggle->isDisabled('feature_name'); // Inverse check
      
    • Twig Integration (if installed):
      {% if 'new_ui' is enabled %}
          <div class="ui-feature">...</div>
      {% endif %}
      
  2. Environment-Specific Config:

    • Override features.yml per environment (e.g., features.prod.yml, features.dev.yml) and load them in config/packages/dev/ecn_feature_toggle.yaml:
      imports:
          - { resource: '%kernel.project_dir%/config/features.dev.yml' }
      
  3. Dependency Injection:

    • Inject FeatureToggle into services/controllers:
      public function __construct(private FeatureToggle $toggle) {}
      
  4. Conditional Logic:

    • Use toggles for A/B testing or gradual rollouts:
      if ($toggle->isEnabled('experimental_search')) {
          $results = $this->searchService->newAlgorithm();
      } else {
          $results = $this->searchService->legacyAlgorithm();
      }
      
  5. Configuration Validation:

    • Validate features.yml via Symfony’s validator (extend Ecn\FeatureToggleBundle\Validator\Constraints\FeatureToggle if needed).

Integration Tips

  1. Database-Backed Toggles (Advanced):

    • Extend the bundle by creating a custom FeatureToggleProvider to fetch toggles from a database (e.g., Doctrine).
    • Override the service in config/services.yaml:
      services:
          Ecn\FeatureToggleBundle\FeatureToggle:
              class: App\Service\CustomFeatureToggleProvider
      
  2. Event-Driven Toggle Updates:

    • Dispatch events when toggles change (e.g., FeatureToggleUpdatedEvent) to invalidate caches or log changes.
  3. Testing:

    • Mock FeatureToggle in tests:
      $this->mock(FeatureToggle::class)->shouldReceive('isEnabled')->andReturn(true);
      
  4. Twig Extensions:

    • Custom Twig filters for complex logic:
      {% if 'feature' is enabled with priority('high') %}
          {# Only show if feature is enabled AND priority is high #}
      {% endif %}
      

Gotchas and Tips

Pitfalls

  1. Configuration Overrides:

    • Issue: Local features.yml overrides Symfony’s default config.
    • Fix: Use imports in config/packages/ecn_feature_toggle.yaml to merge configs:
      ecn_feature_toggle:
          features:
              %ecn_feature_toggle.features%  # Preserve defaults
              new_feature: true               # Override/add
      
  2. Caching:

    • Issue: Toggles are loaded once at bootstrap. Changes to features.yml require a restart.
    • Workaround: Use a cache-warmer or database-backed provider for dynamic updates.
  3. Twig Dependency:

    • Issue: Twig integration is optional but not auto-loaded. Explicitly require twig/twig if using Twig features.
  4. Namespace Collisions:

    • Issue: If you have a feature named App or Service, it may conflict with Symfony’s container.
    • Fix: Use underscores or prefixes (e.g., app_new_ui).
  5. Validation Errors:

    • Issue: Invalid YAML (e.g., unquoted keys) may silently fail.
    • Fix: Validate with symfony/validator or use yaml.lint:
      composer require --dev symfony/validator
      

Debugging Tips

  1. Log Toggle States:

    • Add a debug listener to log toggle evaluations:
      $toggle->enableDebug(true); // If supported (check bundle docs)
      
    • Or manually log:
      \Log::debug('Feature "dark_mode" enabled:', ['status' => $toggle->isEnabled('dark_mode')]);
      
  2. Check Loaded Features:

    • Dump the active features in a controller:
      dump($toggle->getAllFeatures());
      
  3. Environment-Specific Issues:

    • Verify the correct features.yml is loaded per environment by checking:
      $this->container->getParameter('ecn_feature_toggle.features');
      

Extension Points

  1. Custom Providers:

    • Implement Ecn\FeatureToggleBundle\Provider\FeatureToggleProviderInterface for non-YAML sources (e.g., Redis, API).
  2. Event Listeners:

    • Listen for FeatureToggleEvents (if the bundle dispatches them) to react to toggle changes.
  3. Twig Extensions:

    • Extend the Twig environment with custom logic:
      $twig->addFunction(new \Twig\TwigFunction('feature_priority', function ($name, $priority) use ($toggle) {
          return $toggle->isEnabled($name) && $toggle->getPriority($name) >= $priority;
      }));
      
  4. Validation Constraints:

    • Add custom constraints to features.yml:
      ecn_feature_toggle:
          features:
              new_ui:
                  enabled: false
                  constraints:
                      - ValidFeatureName: ~
      
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle