Publish and Subscribe with PHP

How to use

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(\DI\FactoryInterface $factory) {
  3. // create a new publisher that publishes to my-pub-sub component
  4. $publisher = $factory->make(\Dapr\PubSub\Publish::class, ['pubsub' => 'my-pubsub']);
  5. // publish that something happened to my-topic
  6. $publisher->topic('my-topic')->publish(['something' => 'happened']);
  7. });

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\PubSub\Publish $publisher
  4. */
  5. $publisher->topic('my-topic')->publish($raw_data, content_type: 'application/octet-stream');

Binary data

Only application/octet-steam 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.

Last modified January 1, 0001