Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions daprdocs/content/en/php-sdk-docs/php-workflows/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
---
type: docs
title: "Workflows with PHP"
linkTitle: "Workflows"
weight: 1000
description: Manage Dapr workflow instances from PHP
no_list: true
---

The PHP client exposes the Dapr workflow termination and metadata HTTP APIs. Use these methods to stop a running workflow and inspect the reason after it has been terminated.

## Terminate a workflow

Pass a reason to record why an instance was terminated. The reason is optional and is stored as the workflow termination input, exposed through the existing custom-status property.

```php
$client->terminateWorkflow(
workflowComponent: 'dapr',
instanceId: 'order-123',
reason: 'cancelled by operator'
);
```

To terminate a workflow owned by another application in the same namespace, pass its application ID:

```php
$client->terminateWorkflow(
workflowComponent: 'dapr',
instanceId: 'order-123',
reason: 'cancelled by operator',
appId: 'orders'
);
```

A null reason is omitted. Passing an empty string explicitly sends an empty reason.

## Read the termination reason

Retrieve the workflow metadata and read the reason from the `properties` map under `dapr.workflow.custom_status`:

```php
$workflow = $client->getWorkflow(
workflowComponent: 'dapr',
instanceId: 'order-123'
);

$terminationReason = $workflow['properties']['dapr.workflow.custom_status'] ?? null;
```

When no reason is supplied, the existing workflow custom status remains unchanged.

The asynchronous variants are `terminateWorkflowAsync()` and `getWorkflowAsync()`.

## API compatibility

The PHP SDK currently uses Dapr's HTTP workflow API at `/v1.0/workflows`. Dapr marks this HTTP API as deprecated in favor of workflow SDK clients that use gRPC. The PHP SDK does not currently provide a gRPC workflow client.

**Runtime compatibility:** the termination-reason runtime change is still in draft. The Dapr runtime maps the optional `reason` query parameter to its workflow termination request and exposes a supplied reason through `dapr.workflow.custom_status`.
29 changes: 29 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,35 @@ $client->invokeActorMethod(

More detail here: https://docs.dapr.io/developing-applications/building-blocks/actors/actors-overview/

# Workflows

The client can terminate a workflow instance and retrieve its metadata. A runtime with workflow termination-reason support is required to persist the reason and expose it through `dapr.workflow.custom_status`.

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

// The reason is optional and is stored as the workflow termination input, exposed through the existing custom-status property.
$client->terminateWorkflow(
workflowComponent: 'dapr',
instanceId: 'order-123',
reason: 'cancelled by operator'
);

// Read the reason from workflow metadata later.
$workflow = $client->getWorkflow(
workflowComponent: 'dapr',
instanceId: 'order-123'
);

$terminationReason = $workflow['properties']['dapr.workflow.custom_status'] ?? null;
```

Both operations have asynchronous variants: `terminateWorkflowAsync()` and `getWorkflowAsync()`. Pass `appId` to target a workflow hosted by another application in the same namespace, subject to that application's workflow access policy.

The workflow HTTP API is deprecated by Dapr in favor of SDK workflow clients using gRPC. This PHP client currently uses the HTTP API.

**Runtime compatibility:** the termination-reason runtime change is still in draft. The Dapr runtime maps the optional `reason` query parameter to its workflow termination request and exposes a supplied reason through `dapr.workflow.custom_status`.

# Pub/Sub

Delivering events around your application is an important aspect of any application. This is supported by Dapr, and
Expand Down
45 changes: 45 additions & 0 deletions src/lib/Client/DaprClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,51 @@ abstract public function isDaprHealthy(): bool;
*/
abstract public function getMetadata(): MetadataResponse|null;

/**
* Terminate a workflow instance.
*
* @param string $workflowComponent The workflow component name, usually dapr.
* @param string $instanceId The workflow instance ID.
* @param string|null $reason Optional termination reason.
* @param string|null $appId Optional ID of the app hosting the workflow.
*/
abstract public function terminateWorkflow(
string $workflowComponent,
string $instanceId,
?string $reason = null,
?string $appId = null
): void;

/**
* @return PromiseInterface<null>
*/
abstract public function terminateWorkflowAsync(
string $workflowComponent,
string $instanceId,
?string $reason = null,
?string $appId = null
): PromiseInterface;

/**
* Retrieve workflow instance metadata, including the termination reason when present.
*
* @return array<array-key, mixed>
*/
abstract public function getWorkflow(
string $workflowComponent,
string $instanceId,
?string $appId = null
): array;

/**
* @return PromiseInterface<array<array-key, mixed>>
*/
abstract public function getWorkflowAsync(
string $workflowComponent,
string $instanceId,
?string $appId = null
): PromiseInterface;

/**
* Shutdown the Daprd sidecar
*
Expand Down
1 change: 1 addition & 0 deletions src/lib/Client/DaprHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class DaprHttpClient extends DaprClient
use HttpSecretsTrait;
use HttpInvokeTrait;
use HttpPubSubTrait;
use HttpWorkflowTrait;
use HttpBindingTrait;
use HttpActorTrait;
use HttpTokenTrait;
Expand Down
114 changes: 114 additions & 0 deletions src/lib/Client/HttpWorkflowTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
<?php

namespace Dapr\Client;

use Dapr\Deserialization\IDeserializer;
use GuzzleHttp\Client;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;

/**
* HTTP workflow-management operations.
*/
trait HttpWorkflowTrait
{
use PromiseHandlingTrait;

public IDeserializer $deserializer;
protected Client $httpClient;

/**
* Terminates a workflow instance.
*
* The reason is optional and is recorded as the termination input. The runtime
* exposes it through the workflow custom-status property.
*
* @throws \Dapr\exceptions\DaprException
*/
public function terminateWorkflow(
string $workflowComponent,
string $instanceId,
?string $reason = null,
?string $appId = null
): void {
$this->terminateWorkflowAsync($workflowComponent, $instanceId, $reason, $appId)->wait(true);
}

/**
* Terminates a workflow instance asynchronously.
*
* A null reason is omitted from the request. An explicitly empty reason is
* sent as reason=, preserving the distinction between an omitted reason and an explicit empty reason.
*
* @return PromiseInterface<null>
*/
public function terminateWorkflowAsync(
string $workflowComponent,
string $instanceId,
?string $reason = null,
?string $appId = null
): PromiseInterface {
$query = [];
if ($reason !== null) {
$query['reason'] = $reason;
}
if ($appId !== null) {
$query['appID'] = $appId;
}

$options = $query === [] ? [] : ['query' => $query];
$uri = sprintf(
'/v1.0/workflows/%s/%s/terminate',
rawurlencode($workflowComponent),
rawurlencode($instanceId)
);

return $this->handlePromise(
$this->httpClient->postAsync($uri, $options),
static fn(ResponseInterface $response): null => null
);
}

/**
* Gets workflow instance metadata.
*
* The termination reason, when present, is exposed at
* properties['dapr.workflow.custom_status'].
*
* @return array<array-key, mixed>
* @throws \Dapr\exceptions\DaprException
*/
public function getWorkflow(
string $workflowComponent,
string $instanceId,
?string $appId = null
): array {
return $this->getWorkflowAsync($workflowComponent, $instanceId, $appId)->wait();
}

/**
* Gets workflow instance metadata asynchronously.
*
* @return PromiseInterface<array<array-key, mixed>>
*/
public function getWorkflowAsync(
string $workflowComponent,
string $instanceId,
?string $appId = null
): PromiseInterface {
$options = $appId === null ? [] : ['query' => ['appID' => $appId]];
$uri = sprintf(
'/v1.0/workflows/%s/%s',
rawurlencode($workflowComponent),
rawurlencode($instanceId)
);

return $this->handlePromise(
$this->httpClient->getAsync($uri, $options),
fn(ResponseInterface $response): array => $this->deserializer->from_json(
'array',
$response->getBody()->getContents()
)
);
}
}
120 changes: 120 additions & 0 deletions tests/WorkflowTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php

use GuzzleHttp\Psr7\Response;

require_once __DIR__ . '/DaprTests.php';

class WorkflowTest extends DaprTests
{
public function testTerminateWorkflowSendsReasonAndTargetAppId(): void
{
$stack = $this->get_http_client_stack([new Response(202)]);
$client = $this->get_new_client_with_http($stack->client);

$client->terminateWorkflow(
workflowComponent: 'dapr',
instanceId: 'order-123',
reason: 'cancelled by operator',
appId: 'orders'
);

$request = $stack->history[0]['request'];
$this->assertRequestMethod('POST', $request);
$this->assertRequestUri('/v1.0/workflows/dapr/order-123/terminate', $request);
$this->assertRequestBody('', $request);

parse_str($request->getUri()->getQuery(), $query);
$this->assertSame(
['reason' => 'cancelled by operator', 'appID' => 'orders'],
$query
);
}

public function testTerminateWorkflowOmitsAnUnspecifiedReason(): void
{
$stack = $this->get_http_client_stack([new Response(202)]);
$client = $this->get_new_client_with_http($stack->client);

$client->terminateWorkflow('dapr', 'order-123');

$request = $stack->history[0]['request'];
$this->assertRequestMethod('POST', $request);
$this->assertRequestUri('/v1.0/workflows/dapr/order-123/terminate', $request);
$this->assertSame('', $request->getUri()->getQuery());
}

public function testTerminateWorkflowPreservesAnExplicitlyEmptyReason(): void
{
$stack = $this->get_http_client_stack([new Response(202)]);
$client = $this->get_new_client_with_http($stack->client);

$client->terminateWorkflow('dapr', 'order-123', '');

$request = $stack->history[0]['request'];
parse_str($request->getUri()->getQuery(), $query);

$this->assertArrayHasKey('reason', $query);
$this->assertSame('', $query['reason']);
}

public function testTerminateWorkflowAsyncResolvesAfterTheRequestSucceeds(): void
{
$stack = $this->get_http_client_stack([new Response(202)]);
$client = $this->get_new_client_with_http($stack->client);

$result = $client->terminateWorkflowAsync('dapr', 'order-123', 'operator request')->wait();

$this->assertNull($result);
$this->assertRequestMethod('POST', $stack->history[0]['request']);
}

public function testGetWorkflowReturnsMetadataWithTerminationReason(): void
{
$body = json_encode([
'createdAt' => '2026-11-16T00:00:00Z',
'instanceID' => 'order-123',
'lastUpdatedAt' => '2026-11-16T00:01:00Z',
'runtimeStatus' => 'TERMINATED',
'properties' => [
'dapr.workflow.custom_status' => 'cancelled by operator',
],
], JSON_THROW_ON_ERROR);

$stack = $this->get_http_client_stack([new Response(200, body: $body)]);
$client = $this->get_new_client_with_http($stack->client);

$workflow = $client->getWorkflow('dapr', 'order-123', 'orders');

$this->assertSame('TERMINATED', $workflow['runtimeStatus']);
$this->assertSame(
'cancelled by operator',
$workflow['properties']['dapr.workflow.custom_status']
);

$request = $stack->history[0]['request'];
$this->assertRequestMethod('GET', $request);
$this->assertRequestUri('/v1.0/workflows/dapr/order-123', $request);
parse_str($request->getUri()->getQuery(), $query);
$this->assertSame(['appID' => 'orders'], $query);
}

public function testGetWorkflowAsyncReturnsDecodedMetadata(): void
{
$body = json_encode([
'instanceID' => 'order-123',
'runtimeStatus' => 'TERMINATED',
'properties' => [
'dapr.workflow.custom_status' => 'operator request',
],
], JSON_THROW_ON_ERROR);

$stack = $this->get_http_client_stack([new Response(200, body: $body)]);
$client = $this->get_new_client_with_http($stack->client);

$workflow = $client->getWorkflowAsync('dapr', 'order-123')->wait();

$this->assertSame('operator request', $workflow['properties']['dapr.workflow.custom_status']);
$this->assertRequestMethod('GET', $stack->history[0]['request']);
$this->assertSame('', $stack->history[0]['request']->getUri()->getQuery());
}
}