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

Di Env Loader Bundle Laravel Package

bartlomiejbeta/di-env-loader-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bartlomiejbeta/di-env-loader-bundle
    

    Add the bundle to your config/bundles.php:

    return [
        // ...
        BartlomiejBeta\DIEnvLoaderBundle\DIEnvLoaderBundle::class => ['all' => true],
    ];
    
  2. First Use Case:

    • Create a custom Extension (e.g., MyCustomExtension) in a bundle.
    • Use the DIEnvLoaderTrait to load environment-specific configs.
    • Place config files (e.g., services.yml, services_dev.yml) in Resources/config/.

    Example:

    use BartlomiejBeta\DIEnvLoaderBundle\Extension\DIEnvLoaderTrait;
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
    use Symfony\Component\Config\FileLocator;
    
    class MyCustomExtension extends \Symfony\Component\HttpKernel\DependencyInjection\Extension\Extension
    {
        use DIEnvLoaderTrait;
    
        public function load(array $configs, ContainerBuilder $container)
        {
            $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
            self::loadByEnv($loader, $container, 'services', 'yml');
        }
    }
    
    • This loads services.yml (default) and services_<env>.yml (e.g., services_dev.yml for APP_ENV=dev).

Implementation Patterns

Workflows

  1. Default Environment Loading: Use loadByEnv() without conditions to load configs for all environments (e.g., services.yml, services_test.yml).

    self::loadByEnv($loader, $container, 'services', 'yml');
    
    • Files: services.yml, services_<env>.yml (e.g., services_dev.yml).
  2. Environment-Specific Loading: Check the current environment (self::getEnv($container)) and load configs conditionally.

    if ('dev' === self::getEnv($container)) {
        self::loadByEnv($loader, $container, 'services', 'yml', '/dev');
    }
    
    • Files: services_dev.yml (if placed in Resources/config/dev/).
  3. Custom File Locators: Override the default FileLocator path for granular control:

    $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config/custom_path'));
    
  4. Combining with Other Loaders: Chain loadByEnv() with manual loader calls for hybrid configs:

    $loader->load('base_config.yml'); // Always loaded
    self::loadByEnv($loader, $container, 'env_specific', 'yml');
    

Integration Tips

  • Symfony Flex: Works seamlessly with Symfony Flex bundles. Place configs in Resources/config/ and reference them in extensions.
  • Parameter Overrides: Use the loaded configs to override container parameters:
    # services_dev.yml
    parameters:
        app.debug: true
    
  • Testing: Mock self::getEnv() in tests to simulate environments:
    $container->set('kernel.environment', 'test');
    

Gotchas and Tips

Pitfalls

  1. File Naming Conflicts:

    • Avoid naming files ambiguously (e.g., services.yml and services_test.yml in the same dir). The bundle prioritizes <name>_<env>.yml over <name>.yml.
    • Fix: Use explicit paths or separate directories (e.g., Resources/config/dev/services.yml).
  2. Environment Detection:

    • self::getEnv($container) returns the kernel environment (APP_ENV), not the runtime environment (e.g., PHP_SAPI). For runtime-specific logic, use getenv() or $container->getParameter('kernel.environment').
  3. Loader Initialization:

    • Ensure the FileLocator path is correct. A 404 error suggests the path is misconfigured.
    • Debug: Use var_dump($locator->locate('services.yml')) to verify file resolution.
  4. Circular Dependencies:

    • Environment-specific configs might introduce circular references. Use ignore_errors: true in YAML or lazy-loading services:
      services:
          MyService:
              class: App\Service
              calls:
                  - [setConfig, ['%env_config%']]
              lazy: true
      

Debugging

  • Enable Debug Mode: Set APP_DEBUG=1 to see detailed loader errors in Symfony’s profiler or logs.
  • Check Loaded Files: Dump the container’s compiled services to verify configs:
    php bin/console debug:container | grep "env_specific"
    
  • Log Environment: Add a debug dump in your extension:
    file_put_contents(
        __DIR__ . '/../var/log/debug.env',
        'Current env: ' . self::getEnv($container) . PHP_EOL
    );
    

Extension Points

  1. Custom Trait Methods: Extend DIEnvLoaderTrait to add logic (e.g., validate environments):

    protected static function isValidEnv(string $env): bool
    {
        return in_array($env, ['dev', 'prod']);
    }
    

    Then modify loadByEnv() to skip invalid environments.

  2. Loader Decorators: Decorate the YamlFileLoader to preprocess configs:

    $loader = new class($container, $locator) extends YamlFileLoader {
        public function load($resource, string $type = null)
        {
            $content = file_get_contents($resource);
            $content = str_replace('%placeholder%', 'value', $content);
            file_put_contents($resource, $content);
            parent::load($resource, $type);
        }
    };
    
  3. Parameter-Based Paths: Use container parameters to externalize config paths:

    $configPath = $container->getParameter('my_bundle.config_path');
    $loader = new YamlFileLoader($container, new FileLocator($configPath));
    

Configuration Quirks

  • Default Environment: If no <name>_<env>.yml exists, the bundle falls back to <name>.yml. To disable this, override loadByEnv().
  • Case Sensitivity: Environment names are case-sensitive (e.g., devDev). Use strtolower() if needed:
    $env = strtolower(self::getEnv($container));
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui