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

Php Config Printer Laravel Package

symplify/php-config-printer

Print Symfony service and parameter configs to clean PHP files using nikic/php-parser. Generate output for configured services only or full configs (e.g., from YAML arrays) via SmartPhpConfigPrinter and YamlToPhpConverter. Ideal for config transformations and automation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symplify/php-config-printer --dev
    

    Add to composer.json under require-dev to avoid runtime overhead.

  2. First Use Case: Convert a Symfony-style service array to PHP for debugging:

    use Symplify\PhpConfigPrinter\Printer\SmartPhpConfigPrinter;
    
    $config = [
        'App\Service\ExampleService' => [
            'arguments' => ['$param' => 'value'],
            'tags' => ['app.some_tag'],
        ],
    ];
    
    $printer = new SmartPhpConfigPrinter();
    $phpCode = $printer->printConfiguredServices($config);
    file_put_contents('debug/services.php', $phpCode);
    

    Output: A readable PHP file with the service definition.

  3. Where to Look First:

    • Printer/SmartPhpConfigPrinter.php: Core class for converting configs to PHP.
    • ValueObject/PhpConfigPrinterConfig.php: Configuration options (e.g., file paths, formatting).
    • Converter/YamlToPhpConverter.php: For converting YAML configs (e.g., from services.yaml).

Implementation Patterns

Usage Patterns

  1. Debugging Symfony Configs:

    // Dump all configured services to a file
    $printer->printConfiguredServices($container->getServiceDefinitions());
    

    Useful for CI/CD pipelines or local development to inspect service definitions.

  2. YAML-to-PHP Conversion:

    $yaml = file_get_contents('config/services.yaml');
    $converter = new YamlToPhpConverter();
    $phpConfig = $converter->convertYamlString($yaml);
    

    Ideal for teams migrating from YAML to PHP configs or sharing configs with non-Symfony teams.

  3. Integration with Artisan: Create a custom command to generate PHP configs:

    use Illuminate\Console\Command;
    use Symplify\PhpConfigPrinter\Printer\SmartPhpConfigPrinter;
    
    class GenerateConfigCommand extends Command
    {
        protected $signature = 'config:generate';
        protected $description = 'Generate PHP configs from Symfony services';
    
        public function handle(SmartPhpConfigPrinter $printer)
        {
            $config = $this->laravel['container']->getServiceDefinitions();
            $phpCode = $printer->printConfiguredServices($config);
            file_put_contents('storage/config.php', $phpCode);
            $this->info('Config generated!');
        }
    }
    
  4. Partial Configs: Target specific services:

    $partialConfig = [
        'App\Service\ApiClient' => [...],
    ];
    $printer->printConfiguredServices($partialConfig);
    

Workflows

  1. CI/CD Pipeline:

    • Add a step to generate PHP configs from YAML before deployment:
      # .github/workflows/validate-config.yml
      - name: Generate PHP Configs
        run: php artisan config:generate
      - name: Validate PHP
        run: php -l storage/config.php
      
  2. Onboarding:

    • Convert services.yaml to PHP for new developers:
      vendor/bin/php-config-printer config/services.yaml > config/services.php
      
  3. Tooling Integration:

    • Use generated PHP configs in static analyzers (e.g., PHPStan) or custom scripts.

Integration Tips

  1. Laravel-Specific Adaptations:

    • Map Symfony tags to Laravel’s service tags:
      $services = $printer->printConfiguredServices($config);
      $services = preg_replace('/tags.*/', 'tags: [\'app\']', $services); // Example
      
    • Handle Laravel’s bind()/singleton() methods manually after conversion.
  2. Performance:

    • Cache generated configs to avoid repeated parsing:
      if (!file_exists('storage/config.php') || filemtime('config/services.yaml') > filemtime('storage/config.php')) {
          $phpCode = $printer->printConfiguredServices($config);
          file_put_contents('storage/config.php', $phpCode);
      }
      
  3. Testing:

    • Test with a subset of services first:
      $testConfig = ['App\Service\TestService' => [...]];
      $phpCode = $printer->printConfiguredServices($testConfig);
      $this->assertStringContainsString('TestService', $phpCode);
      

Gotchas and Tips

Pitfalls

  1. Symfony Dependency:

    • The package requires Symfony’s DependencyInjection component, which may bloat your project if unused elsewhere.
    • Workaround: Use the package only in dev scripts or isolate it in a separate module.
  2. YAML Parsing Quirks:

    • Complex YAML (e.g., nested factories, dynamic references) may not convert cleanly to PHP.
    • Tip: Validate YAML with Symfony’s Debug\Dumper\CliDumper first:
      php bin/console debug:container --dump
      
  3. Laravel Incompatibility:

    • Symfony’s ContainerConfigurator and services.yaml structure don’t map directly to Laravel.
    • Tip: Use the package for parsing only, then manually adapt to Laravel’s container.
  4. PHP Version:

    • Requires PHP 8.2+. Older Laravel versions (e.g., <9.x) may need updates.
  5. File Overwriting:

    • printConfiguredServices() outputs raw PHP code; ensure target files are writable.

Debugging

  1. Invalid Configs:

    • If parsing fails, check for unsupported Symfony features (e.g., when conditions, factory services).
    • Debug: Use nikic/php-parser directly to isolate the issue:
      use PhpParser\ParserFactory;
      $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
      $parser->parse(file_get_contents('services.yaml'));
      
  2. Output Mismatches:

    • Compare generated PHP with expected output using diff:
      diff <(php artisan config:generate) expected.php
      
  3. Memory Limits:

    • Large configs may hit memory limits. Increase memory_limit or parse incrementally.

Config Quirks

  1. Default Values:

    • Symfony’s _defaults section (e.g., autowire: true) won’t appear in the output unless explicitly defined.
    • Tip: Merge defaults manually:
      $config = array_merge_recursive([
          '_defaults' => ['autowire' => true],
      ], $config);
      
  2. File Paths:

    • PhpConfigPrinterConfig::FILE_PATH defaults to config/php-config-printer.php. Override in services.yaml:
      services:
          _defaults:
              autowire: true
      symplify.php_config_printer:
          file_path: '%kernel.project_dir%/config/printed.php'
      

Extension Points

  1. Custom Printers: Extend SmartPhpConfigPrinter to add Laravel-specific formatting:

    class LaravelPhpConfigPrinter extends SmartPhpConfigPrinter
    {
        protected function formatService(array $service): string
        {
            $formatted = parent::formatService($service);
            // Add Laravel-specific logic (e.g., convert tags to Laravel format)
            return $formatted;
        }
    }
    
  2. Pre/Post-Processing: Hook into the conversion pipeline:

    $converter = new YamlToPhpConverter();
    $phpConfig = $converter->convertYamlString($yaml);
    // Modify $phpConfig before printing
    $printer->printConfiguredServices($phpConfig);
    
  3. Artisan Commands: Create reusable commands for common tasks:

    // app/Console/Commands/ExportConfigs.php
    class ExportConfigs extends Command
    {
        public function handle()
        {
            $configs = [
                'services' => $this->laravel['container']->getServiceDefinitions(),
                'parameters' => $this->laravel['config']->all(),
            ];
            foreach ($configs as $name => $config) {
                file_put_contents("storage/{$name}.php", var_export($config, true));
            }
        }
    }
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor