PHP code example of dapr / php-sdk

1. Go to this page and download the library: Download dapr/php-sdk 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/ */

    

dapr / php-sdk example snippets


$client = \Dapr\Client\DaprClient::clientBuilder()->build();

$app = \Dapr\App::create(configure: [
    // custom configuration
]);
use_middleware($app);



// retrieve a single secret
$client->getSecret(storeName: 'kubernetes', key: 'test');

// retrieve all secrets
$client->getBulkSecret(storeName: 'kubernetes');

['value' => $value, 'etag' => $etag] = $client->getStateAndEtag(storeName: 'statestore', key: 'key', asType: SomeClass::class, consistency: \Dapr\consistency\EventualLastWrite::instance());
$value = $client->getState(storeName: 'statestore', key: 'key', asType: 'string',consistency: \Dapr\consistency\StrongFirstWrite::instance())


#[\Dapr\State\Attributes\StateStore('statestore', \Dapr\consistency\EventualLastWrite::class)]
class MyState {
    /**
     * @var string 
     */
    public string $string_value;
    
    /**
     * @var ComplexType[] 
     */
    #[\Dapr\Deserialization\Attributes\ArrayOf(ComplexType::class)] 
    public array $complex_type;
    
    /**
      * @var SomeObject 
      */
    public SomeObject $object_type;
    
    /**
     * @var int 
     */
    public int $counter = 0;

    /**
     * Increment the counter
     * @param int $amount Amount to increment by
     */
    public function increment(int $amount = 1): void {
        $this->counter += $amount;
    }
}

$app = \Dapr\App::create();
$app->post('/my-state/{key}', function (
    string $key, 
    #[\Dapr\Attributes\FromBody] string $body, 
    \Dapr\State\StateManager $stateManager) {
        $stateManager->save_state(store_name: 'store', item: new \Dapr\State\StateItem(key: $key, value: $body));
        $stateManager->save_object(new MyState);
});
$app->get('/my-state/{key}', function(string $key, \Dapr\State\StateManager $stateManager) {
    return $stateManager->load_state(store_name: 'store', key: $key);
});
$app->start();

$transaction = [
    \Dapr\Client\StateTransactionRequest::upsert(key: 'key', value: $client->serializer->as_json($new_value)),
    \Dapr\Client\StateTransactionRequest::delete(key: 'key');
];
$client->executeStateTransaction(storeName: 'statestore', operations: $transaction);

#[\Dapr\State\Attributes\StateStore('statestore', \Dapr\consistency\StrongFirstWrite::class)]
class SomeState extends \Dapr\State\TransactionalState {
    public string $value;
    public function ok(): void {
        $this->value = 'ok';
    }
}

$app = Dapr\App::create();
$app->get('/do-work', function(SomeState $state) {
    $state->begin();
    $state->value = 'not-ok';
    $state->ok();
    $state->commit();
    return $state;
});
$app->start();


/**
 * Actor that keeps a count
 */
 #[\Dapr\Actors\Attributes\DaprType('ExampleActor')]
interface ICounter {
    /**
     * Increment a counter
     */
    public function increment(int $amount): void;
}



class CountState extends \Dapr\Actors\ActorState {
    public int $count = 0;
}

#[\Dapr\Actors\Attributes\DaprType('Counter')]
class Counter extends \Dapr\Actors\Actor implements ICounter {
    /**
     * Initialize the class
     */
    public function __construct(string $id, private CountState $state) {
        parent::__construct($id);
    }

    /**
     * Increment the count by 1
     */
    public function increment(int $amount): void {
        $this->state->count += $amount;
    }
}

// register the actor with the runtime
$app = \Dapr\App::create(configure: fn(\DI\ContainerBuilder $builder) => $builder->addDefinitions([
    'dapr.actors' => [Counter::class]
]));
$app->start();


use Dapr\Actors\ActorProxy;

 $app = \Dapr\App::create();
 $app->get('/increment/{actorId}[/{amount:\d+}]', function(string $actorId, ActorProxy $actorProxy, int $amount = 1) {
    $counter = $actorProxy->get(ICounter::class, $actorId);
    $counter->increment($amount);
    $counter->create_reminder('increment', new \Dapr\Actors\Reminder('increment', new DateInterval('PT10M'), data: 10 ));
 });
$app->start();

$client->invokeActorMethod(
    httpMethod: 'GET', 
    actor: new \Dapr\Actors\ActorReference(id: 'id', actor_type: 'Counter'), 
    method: 'increment', 
    parameter: 1
 );


$app = \Dapr\App::create();
$app->get('/publish', function(\Dapr\Client\DaprClient $client) {
    $topic = new \Dapr\PubSub\Topic(pubsub: 'pubsub', topic: 'topic', client: $client);
    $topic->publish(['message' => 'arrive at dawn']);
});
$app->start();

$client->publishEvent(pubsubName: 'pubsub', topicName: 'topic', data: ['message' => 'arrive at dawn'], contentType: 'application/json');

$app = \Dapr\App::create(configure: fn(\DI\ContainerBuilder $builder) => $builder->addDefinitions([
    'dapr.subscriptions' => [new \Dapr\PubSub\Subscription('redis-pubsub', 'my-topic', '/receive-message')]
]));
$app->post('/receive-message', function(#[\Dapr\Attributes\FromBody] \Dapr\PubSub\CloudEvent $event) {
 // do something
});
$app->start();

// register a custom type serializer
$app = \Dapr\App::create(configure: fn(\DI\ContainerBuilder $builder) => $builder->addDefinitions([
    'dapr.serializers.custom' => [MyType::class => [MyType::class, 'serialize']],
    'dapr.deserializers.custom' => [MyType::class => [MyType::class, 'deserialize']],
]));

// get the serializer to do manual serializations
$app->get('/', function(\Dapr\Serialization\ISerializer $serializer) {
    return $serializer->as_array('anything here');
});
$app->start();

$client = \Dapr\Client\DaprClient::clientBuilder()
    ->withDeserializationConfig($configuration)
    ->withSerializationConfig($configuration)
    ->build()