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 Schema Laravel Package

event-engine/php-schema

Event Engine PHP Schema provides PHP type definitions to describe and validate event-driven message payloads. Define schemas for commands, events, and queries with reusable types, enabling consistent serialization, documentation, and tooling across your services.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require event-engine/php-schema
    

    Add to composer.json under autoload:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "EventEngine\\Schema\\": "vendor/event-engine/php-schema/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case Define a schema for an event (e.g., UserRegistered):

    use EventEngine\Schema\EventSchema;
    
    $schema = new EventSchema('UserRegistered');
    $schema->addField('user_id', 'integer', true); // Required
    $schema->addField('email', 'string', false);
    $schema->addField('metadata', 'array', false, ['default' => []]);
    

    Validate an event payload:

    $payload = ['user_id' => 123, 'email' => 'test@example.com'];
    $validator = $schema->getValidator();
    $isValid = $validator->validate($payload); // Returns bool
    
  3. Key Files to Explore

    • src/EventSchema.php: Core schema definition logic.
    • src/FieldSchema.php: Field validation rules.
    • src/Validator.php: Payload validation utilities.

Implementation Patterns

Schema Definition Workflows

  1. Reusable Schema Classes Extend EventSchema for domain-specific schemas:

    class UserRegisteredSchema extends EventSchema {
        public function __construct() {
            parent::__construct('UserRegistered');
            $this->addField('user_id', 'integer', true);
            $this->addField('email', 'string', true, ['format' => 'email']);
        }
    }
    
  2. Dynamic Schema Generation Load schemas from a config file (e.g., config/events.php):

    $schemas = config('events.schemas');
    foreach ($schemas as $eventName => $fields) {
        $schema = new EventSchema($eventName);
        foreach ($fields as $name => $config) {
            $schema->addField($name, $config['type'], $config['required']);
        }
    }
    
  3. Integration with Laravel Events Use schemas to validate dispatched events:

    use Illuminate\Support\Facades\Event;
    
    Event::listen('user.registered', function ($payload) {
        $schema = new UserRegisteredSchema();
        if (!$schema->getValidator()->validate($payload)) {
            throw new \InvalidArgumentException('Invalid event payload');
        }
        // Proceed with event logic
    });
    

Validation Patterns

  1. Custom Validators Extend Validator for domain-specific rules:

    use EventEngine\Schema\Validator;
    
    class CustomValidator extends Validator {
        protected function validateCustomRule($value, $rule) {
            return strpos($value, $rule) !== false;
        }
    }
    
  2. Batch Validation Validate multiple events at once:

    $events = [
        ['user_id' => 1, 'email' => 'test@example.com'],
        ['user_id' => 2, 'email' => 'invalid-email']
    ];
    $schema = new UserRegisteredSchema();
    $results = array_map([$schema->getValidator(), 'validate'], $events);
    
  3. Schema Registry Cache schemas for performance:

    $schemaCache = [];
    function getSchema($eventName) {
        if (!isset($schemaCache[$eventName])) {
            $schemaCache[$eventName] = new EventSchema($eventName);
            // Load fields dynamically
        }
        return $schemaCache[$eventName];
    }
    

Gotchas and Tips

Common Pitfalls

  1. Field Type Mismatches

    • The package uses basic PHP types (string, integer, array, etc.). Ensure payload values match exactly (e.g., 1 vs "1" for integers).
    • Fix: Use filter_var() or json_decode() to normalize types before validation.
  2. Circular Dependencies in Schemas

    • If schemas reference each other (e.g., OrderSchema includes UserSchema), validation may fail or hang.
    • Fix: Validate nested schemas separately or flatten payloads.
  3. Missing Default Values

    • Fields with default values in the schema won’t auto-populate in the validator. You must set them manually.
    • Fix: Use array_merge() to apply defaults:
      $payload = array_merge($schema->getDefaults(), $rawPayload);
      
  4. Case Sensitivity

    • Field names in the schema are case-sensitive. Typos in payload keys will cause validation to fail silently.
    • Fix: Normalize keys (e.g., array_change_key_case()) or use a snake_case/camelCase converter.

Debugging Tips

  1. Detailed Validation Errors The validator returns a boolean by default. Enable detailed errors:

    $errors = $schema->getValidator()->validate($payload, true);
    // $errors is an array of field => error messages
    
  2. Schema Dumping Debug schema definitions by dumping the structure:

    dd($schema->getFields()); // Returns associative array of fields
    
  3. Type Coercion Force type coercion during validation:

    $validator = $schema->getValidator();
    $validator->setCoerceTypes(true); // Attempts to cast values to schema types
    

Extension Points

  1. Custom Field Types Extend FieldSchema to support custom types (e.g., uuid):

    class UuidFieldSchema extends FieldSchema {
        public function validate($value) {
            return filter_var($value, FILTER_VALIDATE_UUID) !== false;
        }
    }
    
  2. Plugin System Add pre/post-validation hooks:

    $validator = $schema->getValidator();
    $validator->addPreValidator(function ($payload) {
        // Sanitize or transform payload
    });
    $validator->addPostValidator(function ($payload) {
        // Log or enrich payload
    });
    
  3. Integration with Laravel

    • Service Provider: Bind schemas to the container:
      $this->app->bind(UserRegisteredSchema::class, function () {
          return new UserRegisteredSchema();
      });
      
    • Middleware: Validate incoming API events:
      public function handle($request, Closure $next) {
          $payload = $request->json()->all();
          $schema = app(UserRegisteredSchema::class);
          if (!$schema->getValidator()->validate($payload)) {
              abort(422, 'Invalid event payload');
          }
          return $next($request);
      }
      
  4. Performance Optimization

    • Compile Schemas: Convert schemas to immutable objects for repeated use:
      $compiledSchema = $schema->compile();
      // $compiledSchema is a frozen version of the schema
      
    • Memoization: Cache validated payloads if validation is expensive:
      $cache = new \Symfony\Component\Cache\Adapter\ArrayAdapter();
      $validator = $schema->getValidator();
      $validator->setCache($cache);
      
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