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

Sdk Php Laravel Package

cloudevents/sdk-php

CloudEvents PHP SDK (v1.0) for creating mutable/immutable events, JSON serialize/deserialize, and HTTP marshal/unmarshal in structured, binary, and batch formats. Install via Composer and integrate CloudEvents into your PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require cloudevents/sdk-php:^1.2.0
    

    PHP 8.4+ is now fully supported (previously 8.1+). Ensure ext-curl is available for HTTP transports.

  2. First Use Case: Sending an Event (PHP 8.4 Optimized)

    use CloudEvents\CloudEvents;
    
    // PHP 8.4 constructor property promotion
    $cloudEvents = new CloudEvents(
        specVersion: '1.0',
        logger: null // Optional logger
    );
    
    $event = $cloudEvents->event(
        'com.example.order.created',
        ['orderId' => 123],
        ['source' => 'https://example.com']
    );
    
    // HTTP transport (Guzzle)
    $transport = new \CloudEvents\Transport\Http\GuzzleHttpTransport(
        new \GuzzleHttp\Client(),
        'https://example.com/events'
    );
    $transport->send($event);
    
  3. First Use Case: Receiving an Event

    $transport = new \CloudEvents\Transport\Http\GuzzleHttpTransport(
        new \GuzzleHttp\Client(),
        'https://example.com/events'
    );
    
    $event = $transport->receive();
    if ($event) {
        echo "Received: " . $event->type() . "\n";
        echo "Data: " . json_encode($event->data()) . "\n";
    }
    
  4. Key Files to Explore

    • vendor/cloudEvents/sdk-php/src/ (PHP 8.4-optimized core)
    • tests/ (Updated for PHP 8.4 compatibility)
    • CloudEvents Specification

Implementation Patterns

Common Workflows

1. Event Production (PHP 8.4 Features)

  • Constructor Property Promotion

    // PHP 8.4: Explicit constructor properties
    $cloudEvents = new CloudEvents(
        specVersion: '1.0',
        logger: new \CloudEvents\Logger\VerboseLogger()
    );
    
  • Type-Safe Event Creation

    $event = $cloudEvents->event(
        'com.example.user.updated',
        ['userId' => 42], // Typed data
        ['userAgent' => 'mobile-app'] // Context attributes
    );
    
  • Batch Processing (PHP 8.4 Arrays)

    $batch = $cloudEvents->batch([
        $event1,
        $event2,
    ]);
    $transport->send($batch);
    

2. Event Consumption

  • Validation & Parsing

    $event = $transport->receive();
    if ($event && $event->isValid()) {
        // Process with PHP 8.4 strict typing
        $orderId = $event->data()['orderId'] ?? null;
    }
    
  • Middleware Pipeline (PHP 8.4 Attributes)

    $middleware = new \CloudEvents\Middleware\LogMiddleware();
    $transport->addMiddleware($middleware);
    

3. Laravel Integration (PHP 8.4)

  • Service Provider (Constructor Injection)

    public function register(): void {
        $this->app->singleton(CloudEvents::class, fn () =>
            new CloudEvents(specVersion: '1.0')
        );
    }
    
  • Event Dispatcher Bridge

    class CloudEventDispatcher extends Dispatcher {
        public function dispatchCloudEvent($event): void {
            app(TransportInterface::class)->send($event);
        }
    }
    

4. Testing (PHP 8.4 Mocks)

  • Mock Transports
    $mockTransport = new \CloudEvents\Transport\MockTransport();
    $cloudEvents->setTransport($mockTransport);
    $cloudEvents->send($event);
    $this->assertEquals($event, $mockTransport->lastSentEvent());
    

Gotchas and Tips

Pitfalls

  1. PHP 8.4 Breaking Changes

    • Constructor Signature: CloudEvents now requires explicit named arguments for constructor properties.
      // Old (deprecated)
      $cloudEvents = new CloudEvents();
      $cloudEvents->setSpecVersion('1.0');
      
      // New (PHP 8.4)
      $cloudEvents = new CloudEvents(specVersion: '1.0');
      
    • Deprecated Features: CloudEvents::fromArray() is now CloudEvents::fromData().
      // Old
      $event = CloudEvents::fromArray($data);
      
      // New
      $event = CloudEvents::fromData($data);
      
  2. Binary Data Handling

    • Binary data must be base64-encoded. Use:
      $event = $cloudEvents->eventWithBinaryData(
          'com.example.file.uploaded',
          file_get_contents('file.pdf'),
          ['filename' => 'file.pdf']
      );
      
  3. Transport Timeouts

    • HTTP transports default to 5s. Adjust for PHP 8.4 async contexts:
      $client = new \GuzzleHttp\Client(['timeout' => 30]);
      
  4. Thread Safety

    • Transports (e.g., HTTP clients) may not be thread-safe in PHP 8.4 async workers.
    • Tip: Use Swoole or ReactPHP transports for async.

Debugging

  1. Verbose Logging (PHP 8.4)

    $cloudEvents = new CloudEvents(
        logger: new \CloudEvents\Logger\VerboseLogger()
    );
    
  2. Inspect Raw Events

    $event = CloudEvents::fromData($rawData, validate: false);
    var_dump($event->toArray());
    

Extension Points

  1. Custom Transports (PHP 8.4 Interfaces)

    class SqsTransport implements \CloudEvents\Transport\TransportInterface {
        public function send(CloudEventInterface $event): void { ... }
        public function receive(): ?CloudEventInterface { ... }
    }
    
  2. Middleware (PHP 8.4 Attributes)

    #[Attribute]
    class AuthMiddleware implements MiddlewareInterface {
        public function handle(CloudEventInterface $event, callable $next) {
            return $next($event);
        }
    }
    
  3. Laravel Service Binding

    $this->app->bind(
        TransportInterface::class,
        fn () => new \CloudEvents\Transport\Http\GuzzleHttpTransport(
            new \GuzzleHttp\Client(),
            config('cloud-events.endpoint')
        )
    );
    

Performance Tips

  1. Reuse Transports (PHP 8.4 Singleton)

    $transport = new \CloudEvents\Transport\Http\GuzzleHttpTransport(
        new \GuzzleHttp\Client(['http_version' => '1.1']),
        $url
    );
    
  2. Batch Events

    $batch = $cloudEvents->batch([$event1, $event2]);
    $transport->send($batch);
    
  3. PHP 8.4 JIT Optimization

    • Enable opcache.jit_buffer_size for event-heavy workloads.
  4. PHP 8.4 Named Arguments

    • Leverage named arguments for better readability and IDE support:
      $event = $cloudEvents->event(
          type: 'com.example.event',
          data: ['key' => 'value'],
          attributes: ['source' => 'app']
      );
      
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