PHP code example of cloudevents / sdk-php

1. Go to this page and download the library: Download cloudevents/sdk-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cloudevents / sdk-php example snippets


use CloudEvents\V1\CloudEvent;
use CloudEvents\V1\CloudEventImmutable;

// Immutable CloudEvent
$immutableEvent = new CloudEventImmutable(
    '1n6bFxDMHZFChlI4TVI9tdzphB9',
    '/examples/php-sdk',
    'com.example.type',
    ['example' => 'first-event'],
    'application/json'
);

// Mutable CloudEvent
$mutableEvent = new CloudEvent(
    '1n6bFxDMHZFChlI4TVI9tdzphB9',
    '/examples/php-sdk',
    'com.example.type',
    ['example' => 'first-event'],
    'application/json'
);

// Create immutable from mutable or via versa
$event = CloudEventImmutable::createFromInterface($mutableEvent);
$event = CloudEvent::createFromInterface($immutableEvent);

use CloudEvents\Serializers\JsonDeserializer;
use CloudEvents\Serializers\JsonSerializer;

// JSON serialization
$payload = JsonSerializer::create()->serializeStructured($event);
$payload = JsonSerializer::create()->serializeBatch($events);

// JSON deserialization
$event = JsonDeserializer::create()->deserializeStructured($payload);
$events = JsonDeserializer::create()->deserializeBatch($payload);

use CloudEvents\Http\Marshaller;
use CloudEvents\Http\Unmarshaller;

// Marshal HTTP request
$request = Marshaller::createJsonMarshaller()->marshalStructuredRequest($event);
$request = Marshaller::createJsonMarshaller()->marshalBinaryRequest($event);
$request = Marshaller::createJsonMarshaller()->marshalBatchRequest($events);

// Marshal HTTP response
$request = Marshaller::createJsonMarshaller()->marshalStructuredResponse($event);
$request = Marshaller::createJsonMarshaller()->marshalBinaryResponse($event);
$request = Marshaller::createJsonMarshaller()->marshalBatchResponse($events);

// Unmarshal HTTP message
$events = Unmarshaller::createJsonUnmarshaller()->unmarshal($message);