Custom Serialization

How to configure serialization

Dapr uses JSON serialization and thus (complex) type information is lost when sending/receiving data.

序列化(Serialization)

When returning an object from a controller, passing an object to the DaprClient, or storing an object in a state store, only public properties are scanned and serialized. You can customize this behavior by implementing \Dapr\Serialization\ISerialize. For example, if you wanted to create an ID type that serialized to a string, you may implement it like so:

  1. <?php
  2. class MyId implements \Dapr\Serialization\Serializers\ISerialize
  3. {
  4. public string $id;
  5. public function serialize(mixed $value,\Dapr\Serialization\ISerializer $serializer): mixed
  6. {
  7. // $value === $this
  8. return $this->id;
  9. }
  10. }

This works for any type that we have full ownership over, however, it doesn’t work for classes from libraries or PHP itself. For that, you need to register a custom serializer with the DI container:

  1. <?php
  2. // in config.php
  3. class SerializeSomeClass implements \Dapr\Serialization\Serializers\ISerialize
  4. {
  5. public function serialize(mixed $value,\Dapr\Serialization\ISerializer $serializer) : mixed
  6. {
  7. // serialize $value and return the result
  8. }
  9. }
  10. return [
  11. 'dapr.serializers.custom' => [SomeClass::class => new SerializeSomeClass()],
  12. ];

Deserialization

Deserialization works exactly the same way, except the interface is \Dapr\Deserialization\Deserializers\IDeserialize.