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

Composer Parameter Handler Laravel Package

incenteev/composer-parameter-handler

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package Add to composer.json:

    "require": {
        "incenteev/composer-parameter-handler": "^2.0"
    }
    

    Run composer require incenteev/composer-parameter-handler.

  2. Configure composer.json Define the extra key and hook into Composer scripts:

    "extra": {
        "incenteev-parameters": {
            "file": "config/parameters.yml"  // Path to your target file
        }
    },
    "scripts": {
        "post-install-cmd": ["Incenteev\\ParameterHandler\\ScriptHandler::buildParameters"],
        "post-update-cmd": ["Incenteev\\ParameterHandler\\ScriptHandler::buildParameters"]
    }
    
  3. Create a Dist File Place a .dist template (e.g., config/parameters.yml.dist) with your default parameters under a top-level parameters key:

    parameters:
        app.debug: true
        database.host: localhost
    
  4. First Run Execute composer install or composer update. The package generates parameters.yml from the .dist file, ignoring any non-parameters keys.


First Use Case: Environment-Specific Configs

Use this to manage environment variables (e.g., .env-like secrets) without committing sensitive data to version control. Example workflow:

  1. Commit parameters.yml.dist with placeholders (e.g., database.password: "%env(DB_PASSWORD)%").
  2. Use .gitignore to exclude parameters.yml.
  3. Deploy with composer install to auto-generate parameters.yml from the template.

Implementation Patterns

Workflow Integration

  1. Template-Based Generation

    • Dist File as Source of Truth: Always keep parameters.yml.dist in version control. It defines the structure and defaults.
    • Override Logic: The package merges the .dist file with the existing parameters.yml (if it exists), preserving non-parameters keys (e.g., comments or metadata).
  2. Environment-Specific Handling

    • Conditional Parameters: Use YAML anchors/aliases or Composer environment variables (e.g., %composer.environment%) in .dist files to switch configs per environment.
      parameters:
          app.env: "%composer.environment%"
      
    • Post-Install Hooks: Chain the script with other tasks (e.g., post-install-cmd):
      "scripts": {
          "post-install-cmd": [
              "@vendor/bin/your-custom-script",
              "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters"
          ]
      }
      
  3. Symfony-Like Parameter Handling

    • Laravel Integration: Use the generated parameters.yml with Laravel’s config() helper or a custom config loader:
      $params = yaml_parse(file_get_contents(config_path('parameters.yml'))['parameters'] ?? []);
      config(['app' => array_merge(config('app'), $params)]);
      
  4. Multi-File Support

    • Modular Configs: Split parameters into multiple .dist files (e.g., database.yml.dist, mail.yml.dist) and merge them using a custom script before running the handler.

Advanced Patterns

  1. Dynamic Parameter Injection

    • Composer Plugins: Combine with composer-plugin-api to inject parameters from external sources (e.g., API calls) before generation.
    • Example:
      "scripts": {
          "post-install-cmd": [
              "vendor/bin/your-plugin inject-params",
              "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters"
          ]
      }
      
  2. Parameter Validation

    • Schema Validation: Use a library like symfony/yaml or webmozart/assert to validate the generated parameters.yml against a schema before deployment.
  3. CI/CD Pipelines

    • Automated Secrets: In CI (e.g., GitHub Actions), use parameters.yml.dist with placeholders and replace them with secrets via environment variables:
      # .github/workflows/deploy.yml
      - name: Generate parameters
        run: |
          sed -i "s|%env(DB_PASSWORD)%|${{ secrets.DB_PASSWORD }}|g" config/parameters.yml.dist
          composer install
      

Gotchas and Tips

Pitfalls

  1. File Permissions

    • Issue: Composer may fail to write to parameters.yml if permissions are restrictive.
    • Fix: Ensure the target directory is writable (e.g., chmod -R 775 config/).
  2. Key Collisions

    • Issue: If parameters.yml exists with a parameters key, the package merges it with the .dist file. Unexpected overrides can occur.
    • Fix: Use parameters.yml.dist as the single source of truth and avoid manual edits to parameters.yml.
  3. Non-YAML Files

    • Issue: The package assumes YAML files. Using JSON/INI may break silently.
    • Fix: Stick to YAML or pre-process files into YAML format.
  4. Script Order Dependency

    • Issue: Running the handler before other scripts that modify parameters.yml can lead to race conditions.
    • Fix: Place Incenteev\\ParameterHandler\\ScriptHandler::buildParameters last in post-install-cmd/post-update-cmd.
  5. Case Sensitivity

    • Issue: YAML keys are case-sensitive. Typos in .dist files (e.g., app.Debug vs. app.debug) won’t merge.
    • Fix: Standardize keys in .dist files (e.g., snake_case).

Debugging Tips

  1. Dry Runs

    • Test changes locally with:
      composer install --dry-run
      
    • Check the generated parameters.yml for errors.
  2. Verbose Output

    • Enable Composer’s debug mode to see script execution:
      composer install -v
      
  3. Backup Existing Files

    • Before running composer update, back up parameters.yml to avoid accidental data loss:
      cp config/parameters.yml config/parameters.yml.bak
      

Extension Points

  1. Custom Parameter Sources

    • Override buildParameters: Extend the handler by subclassing ScriptHandler and overriding getParameters() to fetch data from APIs, databases, or other sources.
      class CustomHandler extends \Incenteev\ParameterHandler\ScriptHandler {
          protected function getParameters() {
              $params = parent::getParameters();
              $params['app.custom'] = $this->fetchFromExternalService();
              return $params;
          }
      }
      
    • Register the custom handler in composer.json:
      "scripts": {
          "post-install-cmd": ["CustomHandler::buildParameters"]
      }
      
  2. Pre/Post-Processing

    • Hooks: Use Composer’s pre-scripts to transform .dist files before the handler runs:
      "scripts": {
          "pre-install-cmd": ["vendor/bin/your-script transform-params"],
          "post-install-cmd": ["Incenteev\\ParameterHandler\\ScriptHandler::buildParameters"]
      }
      
  3. Multi-Tenant Parameters

    • Dynamic Paths: Generate tenant-specific parameters.yml files by dynamically setting the file path in extra based on environment variables:
      "extra": {
          "incenteev-parameters": {
              "file": "config/parameters_%tenant_id%.yml"
          }
      }
      
    • Combine with a script to set %tenant_id% before running Composer.

Configuration Quirks

  1. Default Key Name

    • The package defaults to the parameters key. To use a custom key (e.g., config), override the getParametersKey() method in a custom handler.
  2. Non-Standard Dist File Locations

    • The .dist file must be in the same directory as the target file (e.g., parameters.yml.dist next to parameters.yml). Relative paths in extra are resolved from the project root.
  3. Windows Line Endings

    • Issue: YAML files with CRLF line endings may cause parsing errors.
    • Fix: Normalize line endings in .dist files (e.g., using dos2unix or Git’s autocrlf).
  4. Composer Version Compatibility

    • Note: The package works with Composer 1.x and 2.x, but some scripts may need adjustments for Composer 2’s JSON-based config. Test thoroughly.
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