PHP code example of qcodr / restate-sdk-php

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

    

qcodr / restate-sdk-php example snippets


use Qcodr\Restate\Sdk\Context\{Context, ObjectContext, SharedObjectContext};
use Qcodr\Restate\Sdk\Service\Attribute\{Service, VirtualObject, Handler, Shared};

#[Service]
final class Greeter
{
    #[Handler]
    public function greet(Context $ctx, string $name): string
    {
        return "Greetings {$name}";
    }
}

#[VirtualObject]
final class Counter
{
    #[Handler] // exclusive: may write state
    public function add(ObjectContext $ctx, int $delta): int
    {
        $next = ($ctx->get('count') ?? 0) + $delta;
        $ctx->set('count', $next);
        return $next;
    }

    #[Shared] // read-only, concurrent
    public function get(SharedObjectContext $ctx): int
    {
        return $ctx->get('count') ?? 0;
    }
}

use Qcodr\Restate\Sdk\Endpoint\Endpoint;
use Qcodr\Restate\Sdk\Endpoint\ProtocolMode;
use Qcodr\Restate\Sdk\Server\AmpStreamingServer;

$endpoint = Endpoint::builder()
    ->bind(new Greeter())
    ->bind(new Counter())
    ->protocolMode(ProtocolMode::BidiStream)
    ->build();

(new AmpStreamingServer($endpoint))->listen('0.0.0.0', 9080);

use Qcodr\Restate\Sdk\Context\{WorkflowContext, SharedWorkflowContext};
use Qcodr\Restate\Sdk\Service\Attribute\{Workflow, Handler, Shared};

#[Workflow]
final class SignupWorkflow
{
    #[Handler]
    public function run(WorkflowContext $ctx, string $email): string
    {
        $ctx->set('email', $email);
        $token = $ctx->promise('email-verified'); // suspends until resolved
        return "verified:{$email}:{$token}";
    }

    #[Shared]
    public function verify(SharedWorkflowContext $ctx, string $token): void
    {
        $ctx->resolvePromise('email-verified', $token);
    }
}

use Qcodr\Restate\Sdk\Service\{ServiceOptions, HandlerOptions, RetryPolicyOnMaxAttempts};

$endpoint = Endpoint::builder()
    ->bindWithOptions(new Counter(), (new ServiceOptions(
        inactivityTimeoutMillis: 60_000,
        idempotencyRetentionMillis: 86_400_000,
        ingressPrivate: false,
        metadata: ['team' => 'orders'],
    ))->withHandler('add', new HandlerOptions(
        retryPolicyMaxAttempts: 5,
        retryPolicyOnMaxAttempts: RetryPolicyOnMaxAttempts::Pause,
    )))
    ->build();

$endpoint = Endpoint::builder()
    ->bind(new Greeter())
    ->identityKey('publickeyv1_...')   // unsigned/invalid requests → 401
    ->build();

(new AmpStreamingServer($endpoint))->listen('0.0.0.0', 9080, workers: 8); // 0 = one per CPU

new AmpStreamingServer($endpoint, limits: new ServerLimits(
    connectionLimitPerIp: 200,
    streamIdleTimeoutSeconds: 300,
));