Search by

Domain-Driven Design framework for WordPress plugins


README

Tangible DDD is a Domain-Driven Design runtime. It gives each consumer a command/query boundary, transactional event publication, durable asynchronous delivery, causal tracing and long-running orchestration, without making consumers share one database identity.

From 0.9 it ships as four packages in this repository:

Package For
tangible/ddd (this root) WordPress plugins. It bundles ddd-core and ddd-wp. This README is its guide.
tangible/ddd-core The host-neutral runtime, plus a PDO default for plain PHP. Guide: examples/plain-php-durable/README.md
tangible/ddd-symfony Symfony 7.4 on Postgres 16. Guide: examples/symfony/README.md
tangible/ddd-conformance The shared scenario suite (development only)

0.9.2 is the first release of this layout. See CHANGELOG.md for what changed since 0.6.x and how to migrate. Rolling a site back to 0.6.x is covered by docs/runbooks/rollback.md.

For unpublished Symfony packages, follow the consumer installation guide: Composer path repositories need a checkout, so the application's install/update hooks must fetch and verify a pinned revision before package resolution. Requiring the GitHub monorepo root installs the WordPress bundle, not ddd-symfony.

Using tangible-ddd 0.9 on WordPress

Requirements

  • PHP 8.2 or newer
  • WordPress 6.6 or newer (tested on 6.6 and the current release; ADR 0021), with Action Scheduler (woocommerce/action-scheduler, installed by Composer)
  • MySQL 8, or MariaDB 11.4 (the two servers the WordPress path is tested on)
  • A Symfony Dependency Injection container for each top-level consumer

Install and wire

composer require tangible/ddd:^0.9
wp ddd init --prefix=acme_orders --namespace='Acme\Orders'

Keep requiring tangible/ddd, never tangible/ddd-core or tangible/ddd-wp: on WordPress, core always comes from the winning copy. Run wp ddd init from the plugin directory. It creates the DI and table scaffolding and prints the bootstrap snippet to add to your plugin file. The wiring contract (lifecycle, boot(), container, middleware order, tables) is unchanged from 0.6, and docs/wiring-a-consumer.md describes it. A 0.6 consumer runs on 0.9 without code changes.

Commands

Commands enter the command bus. A command opens a wpdb transaction only if it implements ITransactionalCommand. Being on the bus is not an opt-in to a transaction. A plain command has a handler named by convention (Commands\XCommand → CommandHandlers\XHandler). A self-handling command has its handle() dependencies injected from the consumer's container.

namespace Acme\Orders\Application\Commands;

final class PlaceOrderCommand implements ICommand, ITransactionalCommand {
  use CommandBusAware;

  public function __construct(public readonly int $customer_id, public readonly int $total_cents) {}
}

namespace Acme\Orders\Application\CommandHandlers;

final class PlaceOrderHandler implements IReturningCommandHandler {   // 0.9: handle() may return a receipt
  public function __construct(private readonly OrderRepository $orders) {}

  public function handle(ICommand $command): mixed {
    $order = Order::place($command->customer_id, $command->total_cents);   // records OrderPlaced
    $this->orders->save($order);
    return ['order_id' => $order->get_id()];
  }
}

$receipt = (new PlaceOrderCommand(7, 4200))->send();

ICommandHandler::handle(): void stays valid. A receipt is computed before the in-transaction reactions run, so it cannot carry what a reaction creates. Read that back with a query. A command or a synchronous domain-event handler never dispatches another command.

Also new in 0.9, on every host:

  • AggregateRoot and AggregateRootRepository (its final save() persists, then collects the recorded events) for aggregates whose identity is not an int;
  • NotPermittedException, the 403 family;
  • #[Audit(false)] and #[Audit(parameters: false)] on a command class, plus #[Sensitive] and #[NotAudited] on its properties, to control the audit row.

Facts

A domain event recorded by an aggregate is published synchronously, inside the command's unit of work. A fact (an integration event) crosses a consistency boundary through the transactional outbox. Action Scheduler then delivers it on the fact's hook.

final class OrderPlaced extends DomainEvent implements IAnnouncesIntegration {
  public function __construct(public readonly int $order_id) {}
  public function payload(): array { return ['order_id' => $this->order_id]; }
  public function to_integration(): OrderPlacedFact { return new OrderPlacedFact($this->order_id); }
}

final class OrderPlacedFact extends IntegrationEvent {
  public function __construct(public readonly int $order_id = 0) {}
  public function delay(): int { return 0; }   // > 0: due that many seconds after the commit, once
}
  • The constructor parameter names and their types are the wire schema. Treat hook names and payload keys as a cross-plugin API.
  • A delay applies once: 0.6 applied it twice.
  • Type a field that can hold binary data, or a large text, as LargeString. A fact whose Action Scheduler args would exceed 8000 bytes is relayed by reference to its outbox row instead of being refused, as it was in 0.6.

Listeners

An IntegrationListener under Application\IntegrationListeners translates one fact into an optional command. All work belongs in the command's handler.

namespace Acme\Orders\Application\IntegrationListeners;

final class ReserveStockOnOrderPlaced extends IntegrationListener {
  protected function get_event_class(): string { return OrderPlacedFact::class; }

  protected function get_command(IIntegrationEvent $event): ?ICommand {
    return new ReserveStockCommand($event->order_id);
  }
}

What 0.9 adds, once the consumer is at schema v10:

  • Isolation. Each DDD-registered callback runs behind a per-subscriber delivery ledger. If one listener throws, the error is logged and recorded, and the rest of the hook's callbacks still run. Raw add_action callbacks are outside this guarantee.

  • Retries are opt-in. By default a failing listener gets one attempt, as in 0.6. The ledger then marks it exhausted, and wp ddd ops lists it. A listener that declares #[Retries(n)] (TangibleDDD\WordPress\Retries) gets n + 1 attempts through {prefix}_ddd_redeliver, with backoff 30 s × 2ⁿ capped at 3600 s. The option {prefix}_ddd_delivery_attempts sets the number for a whole consumer, and the filter tangible_ddd_delivery_attempts has the last word. Process ignition and resume always keep 5 attempts. This lands in wave 5: see the CHANGELOG. Opt in only when the command can run again for the same fact.

    #[Retries(4)]                                   // 5 attempts in all
    final class ReserveStockOnOrderPlaced extends IntegrationListener { /* ... */ }
  • The fact's identity. Inside a listener, Correlation::current_fact() returns the FactRef (event_id, event_class, correlation_id) of the fact being delivered. Use it, or Uuid::v5(), to derive idempotency keys.

integration_listener() and integration_action() remain the function forms.

Processes

A LongProcess is a series of steps that run in declaration order. Each step returns a Result, which can carry a payload for the next step, commands to dispatch, an await to suspend on, and a checkpoint for compensation. Register process classes privately, tagged ddd.long_process, and call DDDCompilerPasses::register() before compile() (docs/wiring-a-consumer.md).

#[StartsOn(OrderPlacedFact::class)]          // exactly one process per fact, however often it is delivered
#[Awaits(PaymentReceivedFact::class)]
final class FulfilOrderProcess extends LongProcess {
  public function __construct(public readonly int $order_id) { parent::__construct(null); }

  public static function from_event(OrderPlacedFact $e): ?static { return new static($e->order_id); }

  protected function request_payment(): Result {
    return new Result(
      commands: [new RequestPaymentCommand($this->order_id)],
      // the await commits BEFORE the command dispatches; on timeout the completed steps compensate
      await: new AwaitEvent(PaymentReceivedFact::class, ['order_id' => $this->order_id], timeout_seconds: 3600),
    );
  }

  #[RetryStep(attempts: 2, backoff_seconds: 30)]
  protected function ship(mixed $payload, PaymentReceivedFact $paid): Result {
    return new Result(commands: [new ShipOrderCommand($this->order_id, $paid->amount_cents)]);
  }

  #[Compensates('request_payment')]
  protected function cancel(\Throwable $cause, mixed $checkpoint): Result {
    return new Result(commands: [new CancelOrderCommand($this->order_id)]);
  }
}

What 0.9 guarantees on WordPress:

  • A process step never runs without the process lock. A contended wake is re-queued.
  • #[StartsOn] ignition happens once per (process class, fact), including after a dead-letter replay.
  • Every save is version-fenced.
  • A process stranded mid-step shows up in the operator view, with resume and fail repairs.
  • A process whose class no longer decodes is quarantined (failed, with quarantine_reason), and the worker continues.
  • #[RetryStep] re-runs a failed step before the process compensates.
  • $this->step_ref('purpose') gives a key that stays the same when the step re-runs.
  • ProcessRunner::start() inside a command still throws on WordPress. Announce a fact and let #[StartsOn] react instead.

Awaits and alarms

On WordPress, use these:

  • AwaitEvent, unkeyed, matched by criteria;
  • AwaitAll with a key extractor;
  • timeout_seconds on either of them. The timeout is a durable intent with an absolute due time. It is projected to Action Scheduler on the 0.6 hooks with the 0.6 arguments, and a relay tick re-projects it if its action goes missing.

AwaitAlarm::at() and AwaitAlarm::after() (no fact, just time) also run on WordPress, but a 0.6 winner cannot decode them. Avoid them while a rollback to 0.6 is still possible.

The D3 awaits are not supported on WordPress: AwaitEvent::keyed(), AwaitAny, AwaitAll::keyed() and IPrecheckAwait. Their conformance cells are - on wp, and a 0.6 winner could not decode their state. They run on Symfony and plain PHP.

Workflows

BehaviourWorkflow runs configurable, repeatable behaviour routines over work items, through a WorkflowHandler that you subclass. You implement get_workflows(), generate_work_items(), execute_one() and reschedule(). On WordPress, reschedule() is usually a delayed fact that maps back to the handler's command, as tangible-cred's BehaviourWorkflowReschedule does. Its delay now applies once. Fact-ignited workflows (IStartsFromFact, WorkflowIgniter, D10) are not wired on WordPress.

External effects

External effects (IExternalEffectCommand, EffectMiddleware, the effect journal, D1) are not wired on WordPress. A command that calls an external API keeps its own idempotency, as in 0.6. The Symfony and plain-PHP guides show D1.

Operator view and CLI

wp ddd ops                                    # every layer: relay, delivery, wakeup, process
wp ddd ops --layer=delivery --format=json
wp ddd ops --consumer=acme_orders --rearm=timeout:42:3            # re-arm an exhausted wakeup
wp ddd ops --consumer=acme_orders --abandon='<subscriber id> @ <event id>'
wp ddd ops --consumer=acme_orders --resume-stranded=42
wp ddd ops --consumer=acme_orders --fail-stranded=42 --reason='card expired' --compensate
wp ddd relay --once                           # one relay tick: outbox batch, wakeup re-projection, stranded scan
wp ddd drain --before-rollback                # before any rollback to 0.6.x (docs/runbooks/rollback.md)

Each row lists attempts against budget, the last error and the repairs that apply. There is no daemon: Action Scheduler drives delivery, and wp ddd relay --once from cron adds the re-projection and the stranded scan.

Runtime model

  • Commands enter the command bus. Its middleware owns correlation, audit, transaction, domain-event publication and the terminal handler. The stock wpdb transaction middleware opens a database transaction only for commands that implement ITransactionalCommand.
  • Queries use a read-only bus, without the command transaction and the audit bracket.
  • Domain events are synchronous and stay inside the originating unit of work. Integration events cross a consistency boundary through the transactional outbox and Action Scheduler.
  • BehaviourWorkflow runs configurable, repeatable behaviour routines over work items. LongProcess models business lifecycles written by developers: they can schedule, suspend, await integration events, resume and compensate.
  • Long-process definitions are compiled into LongProcessCatalog, so dumped production containers discover the same processes as development containers.
  • Correlation and causation metadata survive cross-plugin handoffs. Opening an exact correlation gathers every registered consumer and stitches their recorded fragments together, without a shared write table.
  • Declared aggregate touches build a rebuildable Biography read model. The touches table is never a write-side authority.

Consumer ownership

Every plugin may bundle its own Composer copy. Each copy registers at plugins_loaded:0, and at priority 1 the loader initializes only the newest registered version. From 0.9 the loader entry is version-unique, so Composer's dedup cannot hide a newer copy. The winner then serves every TangibleDDD\ class itself and reports a mixed load instead of hiding it. Tangible_DDD_Versions::instance()->winner() names the winning copy. Top-level consumers boot against the winner and keep their own namespace root, table prefix, container and storage.

A consumer module is a strict namespace descendant that contributes commands, queries, listeners and long processes through a separate compiled container, while sharing its host consumer's runtime identity. See Consumer modules.

Consumer-scoped storage

For a prefix such as acme_orders, the framework maintains these WordPress tables, each also prefixed with the site's table prefix:

  • acme_orders_integration_outbox, acme_orders_integration_dlq
  • acme_orders_long_processes
  • acme_orders_command_audit
  • acme_orders_touches
  • acme_orders_behaviour_workflows, acme_orders_behaviour_workflows_meta, acme_orders_behaviour_workflow_items
  • from schema v10 (0.9): acme_orders_ddd_wakeups, acme_orders_ddd_delivery_ledger, acme_orders_ddd_relay_pauses

Schema v8 (command_audit.intents, shared with 0.6.13), v10 and v11 are additive only, and a 0.6 copy tolerates them.

Dashboard

The winning copy registers Tangible DDD at the tangible-dddash admin page. The dashboard discovers top-level consumers and reads each one's audit, outbox, process, workflow, touch and trace data. Exact traces are unified across participating consumers and keep consumer provenance. Biography stays scoped to the selected aggregate's owner. The live view uses WordPress Heartbeat to show new trace pieces as workers finish them.

Verifying a change

Every library change must pass the gate before it lands:

composer gate:quick   # no databases, about 30 seconds: run it constantly
composer gate         # everything, about 15-20 minutes: run it before landing

Both run tools/gate.sh, which prints PASS/FAIL per step with its log path and exits non-zero if any step failed. It keeps going after a failure, so one run shows every red step.

Step What Needs
cs php-cs-fixer on the new code —
phpstan, phpstan-core both static configs —
deptrac package boundaries (core must not reach WordPress or Symfony) —
root-unit root unit suite (WordPress stubs, loader, ABI freeze) —
core-unit packages/ddd-core with Composer autoload only —
conformance packages/ddd-conformance --group mem, every scenario on the in-memory host —
example-plain examples/plain-php/run.php —
symfony (full) packages/ddd-symfony: bundle, DBAL/Messenger adapters, its conformance host Postgres 16
wp-integration (full) the WordPress integration suite in a real WordPress Docker, MySQL 8.0, datastream
conformance-wp (full) every scenario on the WordPress host Docker, MySQL 8.0, datastream
core-pdo (full) PDO adapters + every scenario on the PDO host in both prepare modes + the two-process example MySQL 8.0
compat (full) cs, release artifact, loader cases (7.2) and rollback against real 0.6.2/0.6.5/0.6.6 installs (7.3) Docker, MySQL 8.0, datastream, network
wp-integration-maria, conformance-wp-maria (full) the two WordPress suites again, on MariaDB Docker, MariaDB 11.4, datastream
wp-integration-floor (full) the WordPress integration suite on the floor release (WP_FLOOR_VERSION, ADR 0021) Docker, MySQL 8.0, datastream

Environment for the full gate.

  • PHP 8.2+ with pdo_mysql, pdo_pgsql, mysqli; Composer; Docker; git.
  • MySQL 8.0 at DDD_MYSQL_HOST:DDD_MYSQL_PORT (default 127.0.0.1:33306, user root, password DDD_MYSQL_PASSWORD, default ddd). The PDO suite reads the same server through DDD_PDO_HOST/DDD_PDO_PORT/DDD_PDO_USER/DDD_PDO_PASSWORD/ DDD_PDO_DATABASE (same defaults). The harnesses can also start their own pinned MySQL container if DDD_MYSQL_HOST is unset; see tests/harness/lib/common.sh.
  • MariaDB 11.4 at DDD_MARIADB_HOST:DDD_MARIADB_PORT (default 127.0.0.1:33307, user root, password DDD_MARIADB_PASSWORD, default ddd), for the two WordPress suites only. The PDO host is not tested on MariaDB.
  • Postgres 16 through DDD_SF_PG_URL (default pgsql://postgres:ddd@127.0.0.1:55432/<unique>).
  • Every run creates and drops its own databases, so several gates can share one server. Throwaway local servers: docker run -d --name ddd-mysql8 -e MYSQL_ROOT_PASSWORD=ddd -p 33306:3306 mysql:8.0, docker run -d --name ddd-mariadb11 -e MARIADB_ROOT_PASSWORD=ddd -p 33307:3306 mariadb:11.4 and docker run -d --name ddd-pg16 -e POSTGRES_PASSWORD=ddd -p 55432:5432 postgres:16. Test data only, so durability settings such as fsync can be off.
  • .reference/tangible-datastream is optional for the quick gate: the root suite passes without it. The WordPress harnesses need datastream at the commit pinned in tests/harness/refs.lock as their integration host; they take it from the local .reference clone (created by composer install) when it has that commit, otherwise they clone it over SSH, which needs read access to TangibleInc/tangible-datastream (or point DDD_DATASTREAM_SRC at a copy).

Things that trip newcomers.

  • The harnesses test the committed tree (git HEAD), not the working directory. Commit first, or run with DDD_HARNESS_REF=WORKTREE.
  • Stale copies. packages/ddd-symfony and packages/ddd-conformance vendor a copy of ddd-core through path repositories, and ddd-symfony compiles a test container into var/cache that remembers its database URL. The gate removes vendor/tangible and var/cache before those suites; when you run them by hand, do the same, or you test old core code or the wrong database (false failures such as PostCommitWakeupTest, because Postgres NOTIFY does not cross databases).
  • Result cache. The root suite orders tests defects-first from .phpunit.cache. After a random-order run, delete it before a normal run.
  • Slow suites. symfony, core-pdo and compat take about 3-5 minutes each and dominate the full gate; everything else is seconds. The first harness run on a machine is slower: it downloads WordPress, pulls the pinned Docker images and clones datastream.
  • Database names. The harnesses accept only [A-Za-z0-9_] in DDD_DB_NAME.
  • Known flake. ParkedAnswerTest::test_a_parked_answer_held_off_past_the_budget_is_kept_retrying_at_the_cap (ddd-symfony) waits out real lock timeouts and failed once in a loaded run. Re-run it alone with a clean var/cache before treating it as a regression.
  • Serial or parallel. The suites use unique database names, so they can run in parallel against shared servers. One machine-level limit: the harnesses start Docker containers, so don't run two compat gates at once on a small machine.
  • Order independence. The root suite also passes under vendor/bin/phpunit --order-by=random. A test that only fails in some orders is a real defect in its setup or teardown (usually a process-static registry reset on one side only).

Documentation

Historical specs and plans are kept as a record of design decisions, and the documentation map labels them as historical. When a historical record disagrees with the installed package, the current source and tests win.