Publish and Subscribe

With Dapr, you can publish anything, including cloud events. The SDK contains a simple cloud event implementation, but you can also just pass an array that conforms to the cloud event spec or use another library.

  1. <?php
  2. $app->post('/publish', function(\Dapr\Client\DaprClient $daprClient) {
  3. $daprClient->publishEvent(pubsubName: 'pubsub', topicName: 'my-topic', data: ['something' => 'happened']);
  4. });

For more information about publish/subscribe, check out the howto.

Data content type

The PHP SDK allows setting the data content type either when constructing a custom cloud event, or when publishing raw data.

  1. <?php
  2. $event = new \Dapr\PubSub\CloudEvent();
  3. $event->data = $xml;
  4. $event->data_content_type = 'application/xml';
  1. <?php
  2. /**
  3. * @var \Dapr\Client\DaprClient $daprClient
  4. */
  5. $daprClient->publishEvent(pubsubName: 'pubsub', topicName: 'my-topic', data: $raw_data, contentType: 'application/octet-stream');

Binary data

  1. Only <code>application/octet-steam</code> is supported for binary data.

Receiving cloud events

In your subscription handler, you can have the DI Container inject either a Dapr\PubSub\CloudEvent or an array into your controller. The former does some validation to ensure you have a proper event. If you need direct access to the data, or the events do not conform to the spec, use an array.