State Management with PHP

How to use

Dapr offers a great modular approach to using state in your application. The best way to learn the basics is to visit the howto.

Metadata

Many state components allow you to pass metadata to the component to control specific aspects of the component’s behavior. The PHP SDK allows you to pass that metadata through:

  1. <?php
  2. $app->run(
  3. fn(\Dapr\State\StateManager $stateManager) =>
  4. $stateManager->save_state('statestore', new \Dapr\State\StateItem('key', 'value', metadata: ['port' => '112'])));

This is an example of how you might pass the port metadata to Cassandra.

Every state operation allows passing metadata.

Consistency/concurrency

In the PHP SDK, there are four classes that represent the four different types of consistency and concurrency in Dapr:

  1. <?php
  2. [
  3. \Dapr\consistency\StrongLastWrite::class,
  4. \Dapr\consistency\StrongFirstWrite::class,
  5. \Dapr\consistency\EventualLastWrite::class,
  6. \Dapr\consistency\EventualFirstWrite::class,
  7. ]

Passing one of them to a StateManager method or using the StateStore() attribute allows you to define how the state store should handle conflicts.

Parallelism

When doing a bulk read or beginning a transaction, you can specify the amount of parallelism. Dapr will read “at most” that many keys at a time from the underlying store if it has to read one key at a time. This can be helpful to control the load on the state store at the expense of performance. The default is 10.

Prefix

Hardcoded key names are useful, but why not make state objects more reusable? When committing a transaction or saving an object to state, you can pass a prefix that is applied to every key in the object.

  1. <?php
  2. class TransactionObject extends \Dapr\State\TransactionalState {
  3. public string $key;
  4. }
  5. $app->run(function (TransactionObject $object ) {
  6. $object->begin(prefix: 'my-prefix-');
  7. $object->key = 'value';
  8. // commit to key `my-prefix-key`
  9. $object->commit();
  10. });
  1. <?php
  2. class StateObject {
  3. public string $key;
  4. }
  5. $app->run(function(\Dapr\State\StateManager $stateManager) {
  6. $stateManager->load_object($obj = new StateObject(), prefix: 'my-prefix-');
  7. // original value is from `my-prefix-key`
  8. $obj->key = 'value';
  9. // save to `my-prefix-key`
  10. $stateManager->save_object($obj, prefix: 'my-prefix-');
  11. });