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

Yaml Classer Laravel Package

achinon/yaml_classer

Symfony bundle that converts YAML config files into generated PHP classes, enabling IDE-friendly, callable access to YAML values. Install via Composer, run a console command to generate a class, then use via DI or instantiate directly.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require achinon/yaml_classer in your Laravel project. Ensure the package is autoloaded (check composer.json and run composer dump-autoload if needed).

  2. First Command Generate a class from a YAML file:

    php artisan achinon:yaml_classer path/to/config.yml ConfigClassName
    

    Example:

    php artisan achinon:yaml_classer config/services.yml App\Config\ServicesConfig
    
  3. First Use Case Use the generated class in your Laravel app:

    // Via DI (if registered as a service)
    public function __construct(App\Config\ServicesConfig $servicesConfig) {
        $this->mailer = $servicesConfig->get('mail.mailers.smtp.host');
    }
    
    // Or instantiate directly
    $config = new App\Config\ServicesConfig();
    $value = $config->example; // Access nested values like YAML keys
    

Implementation Patterns

Usage Patterns

  1. Config Management

    • Replace hardcoded YAML paths with generated classes for autocompletion and type safety.
    • Example: Convert config('services.mail.host') to $mailConfig->mail->host.
  2. Dependency Injection

    • Register the generated class as a service provider:
      // In AppServiceProvider@boot()
      $this->app->singleton(App\Config\ServicesConfig::class, function ($app) {
          return new App\Config\ServicesConfig();
      });
      
    • Inject into controllers/services:
      public function __construct(App\Config\ServicesConfig $config) {
          $this->config = $config;
      }
      
  3. Dynamic Configuration

    • Use the class to validate or merge YAML configs at runtime:
      $userConfig = new App\Config\UserSettings();
      if (!$userConfig->get('feature.enabled')) {
          // Disable feature logic
      }
      
  4. IDE Integration

    • Leverage autocompletion for nested YAML keys (e.g., $config->database-> shows host, port).
    • Use PHPStan/PSR-12 to enforce type hints for config values.

Workflows

  • Development Workflow

    1. Edit YAML files (e.g., config/custom.yml).
    2. Regenerate classes with the same command (overwrites existing files).
    3. Restart IDE for autocompletion updates.
  • Deployment Workflow

    • Commit generated classes to version control (if YAML is static).
    • Or regenerate classes during deployment (if YAML changes frequently).

Integration Tips

  • Laravel Config Integration Extend the package to load YAML from config/ and generate classes automatically:

    // In a custom Artisan command
    $yamlFiles = File::allFiles(config_path());
    foreach ($yamlFiles as $file) {
        $className = 'App\Config\\' . basename($file, '.yml');
        $this->call('achinon:yaml_classer', [
            'file' => $file->getPathname(),
            'class' => $className,
        ]);
    }
    
  • Caching Cache generated classes in bootstrap/cache/ to avoid regeneration on every request.


Gotchas and Tips

Pitfalls

  1. File Overwrites

    • The command overwrites existing files without warning. Use --dry-run (if available) or check for files manually before running.
  2. Namespace Collisions

    • Ensure generated class names (e.g., ConfigClassName) don’t conflict with existing classes. Prefix with your app namespace (e.g., App\Config\).
  3. YAML Parsing Quirks

    • Complex YAML (e.g., anchors, tags, or multi-document files) may not parse correctly. Test edge cases like:
      # May fail
      defaults: &defaults
        adapter: mysql
        host: localhost
      production:
        <<: *defaults
        host: db.prod.example.com
      
  4. IDE Autocompletion Lag

    • Regenerating many classes may slow down your IDE. Use .gitignore to exclude generated files if they’re not critical.

Debugging

  • Class Not Found? Verify the generated file is in the autoloaded namespace (check composer.json under autoload->psr-4).

  • Property Access Errors Debug with:

    var_dump((new App\Config\ServicesConfig())->toArray());
    

    Compare with the original YAML to spot parsing issues.

  • Command Not Found Ensure the package is registered in config/console.php:

    'commands' => [
        \Achinon\YamlClasserBundle\Command\GenerateClassCommand::class,
    ],
    

Tips

  1. Custom Class Templates Extend the package to generate classes with:

    • Type hints (e.g., public string $host).
    • Getter/setter methods:
      public function getHost(): string { return $this->host; }
      
  2. Validation Layer Add validation to generated classes:

    public function __construct() {
        if (empty($this->example)) {
            throw new \RuntimeException("Config 'example' is required.");
        }
    }
    
  3. Environment-Specific Configs Generate separate classes for config.yml and config.prod.yml:

    php artisan achinon:yaml_classer config.yml App\Config\Config
    php artisan achinon:yaml_classer config.prod.yml App\Config\ProdConfig
    
  4. Performance For large YAML files, optimize by:

    • Lazy-loading properties (e.g., __get() magic method).
    • Using Yaml::parseFile() directly if the package becomes a bottleneck.
  5. Testing Mock generated classes in tests:

    $mockConfig = $this->createMock(App\Config\ServicesConfig::class);
    $mockConfig->method('get')->willReturn('test-value');
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui