Guides

Using Services & SdkContext

Intermediate~8 min

Access runtime services through SdkContext and the built-in helper traits instead of custom containers or WordPress globals.

Prerequisites

  • A module that already extends AbstractModule.
  • Comfort overriding onSdkReady(SdkContext $ctx).
  • At least one feature that needs settings, HTTP, events, cache, or logging.

What You Will Finish With

  • Read and write runtime services from SdkContext.
  • Choose between direct service access and helper traits.
  • Combine caching, HTTP, and events without adding a custom container.

The service surface

SdkContext exposes the current runtime service interfaces: settings, cache, http, logger, events, channel, license, tokens, scheduler, and storage.

public function onSdkReady(SdkContext $ctx): void
{
    parent::onSdkReady($ctx);

    $ctx->logger()->info('analytics.boot', []);
    $settings = $ctx->settings()?->all() ?? [];
    $licensed = $ctx->license()?->isActive() ?? false;
}

Caching remote data

Pair CacheServiceInterface with HttpServiceInterface to avoid repeated remote calls on every admin request.

public function refreshStats(SdkContext $ctx): array
{
    $cached = $ctx->cache()?->get('dashboard_stats');
    if (is_array($cached)) {
        return $cached;
    }

    $stats = $ctx->http()?->get('https://api.example.com/stats') ?? [];
    $ctx->cache()?->set('dashboard_stats', $stats, 300);

    return $stats;
}

Events

Use the in-process event bus for cross-module notifications. emit() publishes events; on() and once() subscribe to them.

public function onSdkReady(SdkContext $ctx): void
{
    parent::onSdkReady($ctx);

    $ctx->events()?->on('payment.completed', [$this, 'handlePayment']);
}

public function createOrder(SdkContext $ctx, int $orderId): void
{
    $ctx->events()?->emit('order.created', [
        'order_id' => $orderId,
    ]);
}

Traits

AbstractModule already mixes in the runtime helper traits. That gives you setSetting(), registerGetRoute(), scheduleCron(), requireCapability(), and notice helpers without extra setup.