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

Interop Config Laravel Package

sandrokeil/interop-config

Framework-agnostic PHP library for configuration-driven factories. Validates config structure, merges defaults, enforces required options, reduces factory boilerplate, supports auto-discovery of factories, and can generate configuration files from factory classes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation (PHP 8+ required):

    composer require sandrokeil/interop-config
    

    Add to composer.json under require if not auto-loaded.

  2. First Look:

    • Core classes: InteropConfig\ConfigInterface, InteropConfig\Config, InteropConfig\FactoryInterface.
    • Key files: src/Config.php, src/Factory.php (check vendor/sandrokeil/interop-config).
    • PHP 8 Features: Leverage named arguments and constructor property promotion if extending the package.
  3. First Use Case (unchanged): Define a config structure (e.g., config/my_module.php):

    return [
        'required_option' => env('REQUIRED_VALUE', 'default'),
        'optional' => [
            'nested' => 'value',
        ],
    ];
    

    Create a factory class (e.g., app/Modules/MyModule/MyModuleFactory):

    use InteropConfig\FactoryInterface;
    
    class MyModuleFactory implements FactoryInterface {
        public function create(array $config) {
            return new MyModule($config['required_option'], $config['optional'] ?? []);
        }
    }
    

    Register the factory in a service provider:

    $this->app->bind('my.module', function ($app) {
        return $app->make(FactoryInterface::class)
            ->create(config('my_module'));
    });
    

Implementation Patterns

Workflows

  1. Config-Driven Instantiation (unchanged):

    • Use Config class to enforce structure and validate mandatory fields:
      $config = new \InteropConfig\Config([
          'required' => 'value',
          'optional' => null,
      ], ['required']); // 'required' is mandatory
      
    • Pass validated config to factories for instantiation.
  2. Factory Integration (unchanged):

    • Implement FactoryInterface for custom logic:
      class UserFactory implements FactoryInterface {
          public function create(array $config) {
              return new User(
                  $config['name'],
                  $config['email'] ?? 'default@example.com'
              );
          }
      }
      
    • Bind factories to Laravel’s container for dependency injection.
  3. Uniform Config Structure (unchanged):

    • Enforce consistency across modules by validating all configs via Config class.
    • Example: Validate nested arrays recursively:
      $config = new \InteropConfig\Config($rawConfig, [
          'users.*' => ['name', 'email'], // Mandatory for each user
      ]);
      

Integration Tips

  • Service Providers (unchanged): Bind factories early in the boot process to ensure configs are validated before use:
    public function boot() {
        $this->app->singleton(FactoryInterface::class, function ($app) {
            return new MyModuleFactory();
        });
    }
    
  • Dynamic Configs (unchanged): Use Config::validate() for runtime checks (e.g., API payloads):
    $validated = \InteropConfig\Config::validate($request->all(), ['required_field']);
    
  • Testing (unchanged): Mock FactoryInterface to test instantiation logic:
    $factory = Mockery::mock(FactoryInterface::class);
    $factory->shouldReceive('create')->once()->andReturn(new MyClass());
    $this->app->instance(FactoryInterface::class, $factory);
    

Gotchas and Tips

Pitfalls

  1. Mandatory Field Validation (unchanged):

    • Forgetting to declare mandatory fields in Config constructor throws InvalidArgumentException.
    • Fix: Always pass an array of required keys to Config:
      new \InteropConfig\Config($data, ['key1', 'key2.nested']);
      
  2. Nested Array Handling (unchanged):

    • Nested mandatory fields (e.g., users.*.email) require precise dot notation.
    • Fix: Use Config::validate() with recursive checks:
      $config = \InteropConfig\Config::validate($data, [
          'users.*' => ['email', 'name'],
      ]);
      
  3. Factory Binding Overrides (unchanged):

    • Binding a factory to the container replaces existing bindings.
    • Fix: Use when() or unless() in service providers for conditional binding.
  4. Legacy Configs (unchanged):

    • Existing configs without mandatory fields may break after migration.
    • Fix: Gradually introduce validation by updating Config instantiation.

Debugging

  • Validation Errors (unchanged): Check the exception message for missing/malformed keys. Example:
    The "required_key" key is required in the config.
    
  • Factory Instantiation (unchanged): Use dd($config) inside create() to inspect passed data.

Extension Points

  1. Custom Validators (updated for PHP 8): Extend Config by overriding validate() or adding static methods. Leverage PHP 8 features like named arguments:
    class ExtendedConfig extends \InteropConfig\Config {
        public static function validateEmail(array $data, string $field = 'email') {
            return self::validate($data, [$field]);
        }
    }
    
  2. Dynamic Factories (updated for PHP 8): Use closures for runtime factory resolution with PHP 8’s improved closure syntax:
    $this->app->bind('dynamic.factory', fn(array $config) => new DynamicClass($config));
    
  3. Config Merging (unchanged): Combine configs from multiple sources (e.g., environment + cache):
    $merged = array_merge(
        config('default'),
        cache('custom_config')
    );
    $config = new \InteropConfig\Config($merged, ['required']);
    
  4. PHP 8-Specific Optimizations:
    • Use constructor property promotion when extending Config or FactoryInterface:
      class MyFactory implements FactoryInterface {
          public function __construct(private array $defaultConfig) {}
      
          public function create(array $config) {
              return new MyClass(array_merge($this->defaultConfig, $config));
          }
      }
      
    • Leverage named arguments for clarity in method calls:
      $config = new \InteropConfig\Config(
          $data,
          requiredFields: ['required_key'],
          optionalFields: ['optional_key']
      );
      
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.
terminal42/code-quality-tools
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