Temporal PHP SDK

repository·master·Indexed 19 days ago

https://github.com/temporalio/sdk-php

A framework for authoring distributed, scalable, and durable Workflows and Activities using PHP. The SDK consists of Clients for managing workflows (requiring ext-grpc) and Workers for executing them (requiring RoadRunner). It includes tools for activity configuration via ActivityOptions and LocalActivityOptions, a ServiceClient for namespace and execution management, and a testing toolkit featuring activity mocking and a Replay API.

Tokens
8.7K
Snippets
22
Records
38
Agent score
64%

What's inside temporalio-sdk-php

  1. Debug Workflows and Activities with Buggregator

    master

    Because Workflows and Activities run in RoadRunner workers, standard output functions like var_dump, print_r, or echo will not work. Instead, use Buggregator with Trap to view dumps, traces, and logs in a web interface.

    Running Buggregator via Docker

    docker run --rm -p 8000:8000 -p 1025:1025 -p 9912:9912 -p 9913:9913 ghcr.io/buggregator/server:latest

    Running Trap locally

    If not using Docker, you can run Trap as a compact server:

    ./vendor/bin/trap --ui=8000

    Once set up, use the trap(), tr(), or dump() functions to output data. The Web UI will be available at http://localhost:8000.

  2. How to use the Temporal PHP SDK

    master

    The SDK can be used with or without framework integrations:

    • Spiral Framework: If you are using Spiral, follow the specific Spiral documentation.
    • Standalone: If using the SDK without integrations, refer to the following guides:
      • How to run Worker Processes
      • How to develop a basic Workflow
      • How to connect a Temporal Client to a Temporal Service
      • How to start a Workflow Execution

    For practical implementation, check out the official samples repository.

  3. Start a local Temporal Service with Temporal CLI

    master

    The Temporal CLI includes an embedded Temporal Service (Server, SQLite persistence, and Web UI) suitable for development and CI/CD. Use the following command to start it in development mode:

    temporal server start-dev --log-level error
  4. Test Workflows in PHP

    master

    The PHP SDK provides a toolkit for testing Workflows. Key capabilities include:

    • Activity Mocking: Testing Workflows by mocking their dependencies.
    • Replay API: Using the Replay API in tests to ensure Workflow determinism.
  5. Install the Temporal PHP SDK

    master

    Install the SDK using Composer. The SDK consists of two main components:

    1. Clients: Used to start, schedule, and manage Workflows. Requires the grpc extension.
    2. Workers: Used to execute Workflows and Activities. Requires RoadRunner.

    For production performance, it is highly recommended to use the protobuf extension for both components.

    ComponentRoadRunnerext-grpcext-protobuf
    Clientrequiredrecommended
    Workerrequiredrecommended
    composer require temporal/sdk
  6. Manage Worker Deployments and Versions

    master

    The ServiceClient provides methods to manage worker deployments, which allow for versioned deployments and controlled rollouts (ramping).

    Key Operations:

    • List Deployments: Use ListWorkerDeployments to see all deployments in a namespace. (Note: ListDeployments is deprecated).
    • Describe Deployment: Use DescribeWorkerDeployment to get details about a specific deployment, or DescribeWorkerDeploymentVersion for a specific version.
    • Set Current Version: Use SetWorkerDeploymentCurrentVersion to set the active version for a deployment series. This automatically unsets any active Ramping Version.
    • Ramping/Rollouts: Use SetWorkerDeploymentRampingVersion to set a version to be rolled out gradually with a specific ramp percentage.
    • Cleanup: Use DeleteWorkerDeployment to remove a deployment (must have no versions) or DeleteWorkerDeploymentVersion to manually delete a specific version.

    Conditions for deleting a version:

    • It is not the Current or Ramping Version.
    • It has no active pollers (no task queues in that version have pollers).
    • It is not draining (unless skip-drainage=true is passed).

    Deprecated Methods:

    • ListDeployments -> Use ListWorkerDeployments.
    • GetDeploymentReachability -> Use DrainageInfo returned by DescribeWorkerDeploymentVersion.
    • GetCurrentDeployment -> Use current_version returned by DescribeWorkerDeployment.
    • SetCurrentDeployment -> Use SetWorkerDeploymentCurrentVersion.
  7. Worker Versioning and Build ID Management

    master

    Temporal supports Worker Versioning to manage deployments and rollouts.

    Note: Worker Versioning is not yet stable; APIs and behavior may change incompatibly.

    • UpdateWorkerVersioningRules: Manages rules for a Task Queue, including Build ID Assignment (how new executions are assigned to Build IDs) and Compatible Build ID Redirect (moving workflows from one Build ID to another).
    • GetWorkerVersioningRules: Fetches the current assignment and redirect rules for a Task Queue.

    Deprecated Methods:

    • UpdateWorkerBuildIdCompatibility: Replaced by UpdateWorkerVersioningRules.
    • GetWorkerBuildIdCompatibility: Replaced by GetWorkerVersioningRules.
  8. How activity timeouts work

    master

    When configuring ActivityOptions, you have two primary ways to manage timeouts:

    1. End-to-End Timeout: Use withScheduleToCloseTimeout($timeout). This is a single value that covers the entire lifecycle of the activity, including the time it spends waiting in the task queue and its actual execution time.

    2. Granular Timeouts: If you do not provide a ScheduleToCloseTimeout, you must provide both:

      • withScheduleToStartTimeout($timeout): Limits how long the activity can sit in the queue.
      • withStartToCloseTimeout($timeout): Limits how long the actual execution can take.

    Using withScheduleToCloseTimeout is generally simpler for defining a total maximum duration for an activity's lifecycle.

  9. Use EncodedCollection to manage encoded data

    master

    The EncodedCollection class is an associative collection used to manage data that has been encoded for transport (as Payload objects) or raw values that need encoding. It acts as a bridge between your application's typed values and the Temporal Payload format.

    Key behaviors:

    • It can hold both raw values (to be encoded) and existing Payload objects (to be decoded).
    • It requires a DataConverterInterface implementation to perform the actual encoding/decoding of values to/from Payload objects.
    • It is immutable when using withValue(), returning a new instance instead of modifying the existing one.
    • It implements IteratorAggregate and Countable, allowing you to loop over decoded values or check the collection size.
    use Temporal\DataConverter\EncodedCollection;
    
    // Create from raw values
    $collection = EncodedCollection::fromValues(['key' => 'value'], $dataConverter);
    
    // Add or replace a value (returns a new instance)
    $newCollection = $collection->withValue('new_key', 123);
    
    // Access a decoded value
    $value = $newCollection->getValue('key');
  10. Configure Temporal Client options

    master

    The ClientOptions class is used to configure the behavior of a Temporal Client. It uses an immutable pattern where calling a with* method returns a new instance of ClientOptions with the updated value.

    Key configuration properties include:

    • namespace: The Temporal namespace to use. Defaults to 'default'.
    • identity: A unique identifier for the client. By default, this is generated using the current process ID and hostname (<pid>@<hostname>).
    • queryRejectionCondition: An integer value determining when queries should be rejected. This should be a valid value from the Temporal\Api\Enums\V1\QueryRejectCondition enum.
    use Temporal\Client\ClientOptions;
    use Temporal\Api\Enums\V1\QueryRejectCondition;
    
    $options = (new ClientOptions())
        ->withNamespace('my-namespace')
        ->withIdentity('my-custom-identity')
        ->withQueryRejectionCondition(QueryRejectCondition::QUERY_REJECT_CONDITION_NONE);
  11. Configure LocalActivityOptions for activities

    master

    Use LocalActivityOptions to define timeouts and retry policies for activities executed within a workflow. Local activities are managed by the workflow worker and are subject to the following configuration options:

    Timeouts

    • ScheduleToCloseTimeout: The end-to-end timeout for the activity. If not explicitly set, the default is the sum of scheduleToStartTimeout and startToCloseTimeout. Use withScheduleToCloseTimeout($timeout) to set this.
    • StartToCloseTimeout: The maximum time allowed from the start of activity execution to its completion. Use withStartToCloseTimeout($timeout) to set this.

    Retry Policy

    • RetryOptions: Specifies how to retry an activity if it fails. If no RetryOptions are provided, the Temporal server provides a default policy:
      • InitialInterval: 1 second
      • BackoffCoefficient: 2.0
      • MaximumInterval: 100 x InitialInterval
      • MaximumAttempts: 0 (unlimited)

    To disable retries, set MaximumAttempts to 1. Use withRetryOptions(?RetryOptions $options) to configure this.

    Summary (Experimental)

    • Summary: An optional single-line fixed summary for the activity that appears in the Temporal UI or CLI. Supports single-line Temporal Markdown. Use withSummary(string $summary) to set this.
    use Temporal\Activity\LocalActivityOptions;
    use Temporal\Common\RetryOptions;
    
    $options = (new LocalActivityOptions())
        ->withStartToCloseTimeout(new \DateInterval('PT10S'))
        ->withRetryOptions(RetryOptions::new()->withMaximumAttempts(3));