Skip to main content

PHP SDK

note

This is a platform SDK — it covers the full Kilimanjaro API surface: data, auth (Gate IAK), migrations, functions, policies, audit, org management, and realtime. A separate mobile SDK family exists for auth-only mobile use cases.

The k9o/sdk package brings the full Kilimanjaro platform to PHP. Every API pillar — structured data, realtime subscriptions, object storage, Gate IAK authentication, RBAC, audit log, and serverless functions — is available through a single, PSR-aligned client.

Runtime baseline. PHP 8.5.12 or later. The SDK uses readonly classes for immutable response types, named arguments at call sites, and Generator-backed streaming. It aligns with PSR-7 (HTTP messages), PSR-18 (HTTP client), and PSR-3 (logging) — bring your own HTTP client and logger, or rely on the bundled Guzzle-based defaults.


Installation​

composer require k9o/sdk

Minimum requirement: PHP 8.5.12, which carries the fixes for CVE-2026-109618 and CVE-2026-109619. The package declares no framework dependency; Laravel and Symfony service-provider packages are available as optional companions (k9o/laravel and k9o/symfony-bundle).


Setup​

Construct the client with base_url, API key, org slug, and project slug. base_url is optional — the default is https://api.k9o.io; when you supply the bare apex together with org_slug, the SDK derives the canonical org-scoped base URL (https://<orgSlug>.api.k9o.io) for you. The snippet below shows the explicit subdomain form for clarity; either style works.

PHP
<?php

use K9o\K9oClient;

$k9o = K9oClient::create([
  'base_url'     => 'https://acme.api.k9o.io', // optional
  'api_key'      => getenv('K9O_API_KEY'),
  'org_slug'     => 'acme',
  'project_slug' => 'member-portal',
]);

Showing example in PHP

API key source. Read the key from an environment variable — never hard-code it in source. The K9O_API_KEY convention is idiomatic; use whichever env-var name your deployment tooling supports.

Self-hosted and Sovereign deployments. Pass your own host as base_url instead of the Kilimanjaro Cloud subdomain when you run Kilimanjaro on your own infrastructure:

PHP
<?php

use K9o\K9oClient;

$k9o = K9oClient::create([
  'base_url'     => 'https://platform.acme.internal',  // host only — no path
  'org_slug'     => 'acme',
  'project_slug' => 'member-portal',
  'api_key'      => getenv('K9O_API_KEY'),
]);

Showing example in PHP

When supplying base_url, it must be a scheme://host value with no path component. Supplying a path-bearing URL (for example https://api.k9o.io/v2) throws K9O_INVALID_BASE_URL at construction time, not on the first request.


Getting started​

The first operation most applications make is querying a data collection — build a query, execute it, and handle KError. Signing users in has its own section below.

PHP
<?php

use K9o\K9oClient;
use K9o\KError;

$k9o = K9oClient::create([
  'base_url'     => 'https://acme.api.k9o.io', // optional
  'api_key'      => getenv('K9O_API_KEY'),
  'org_slug'     => 'acme',
  'project_slug' => 'member-portal',
]);

try {
  $response = $k9o->from('posts')->select()->limit(10)->execute();
  foreach ($response->data as $row) {
      echo json_encode($row), PHP_EOL;
  }
  // Pagination cursor — null on the final page.
  echo "next cursor: {$response->meta->cursor?->next}\n";

} catch (KError $e) {
  fwrite(STDERR, "[{$e->code}] {$e->getMessage()}\n");
}
Output · bash
{"id":"post_1","title":"Hello"}
next cursor:

Showing example in PHP

$k9o->from('posts')->select() executes the query builder against the posts collection in your project's data schema (ch04). The result is always {data, meta} — $response->data is an array of row maps (array<string, mixed> per PHPDoc); $response->meta->cursor?->next is the opaque pagination cursor for the next page, or null on the last page.

For the full query builder surface (filters, limit, cursor, count) see the API reference.


Authenticating your End-Users​

This server SDK covers password sign-in and session management: signIn, signUp, signOut, whoami, and refreshToken. Social identity-provider (OAuth2/SAML) and passwordless (magic-link / OTP) flows are browser and mobile flows that depend on window.location redirects — they live on the TypeScript SDK and the mobile SDKs only. See those pages, or the Auth API reference, for the full Gate surface. revokeAllSessions ends every session of the signed-in user, this device included; access tokens already issued live until they expire. See Session lifetime and sign-out.

Password
<?php

$result = $k9o->gate->sign_in(email: '[email protected]', password: '…');
echo "signed in: {$result->data['user']['id']}\n";        // eu_<base62>
echo "access token: {$result->data['session']['accessToken']}\n";
Output · bash
signed in: eu_8f3kQ2mZ
access token: eyJhbGciOiJSUzI1NiIs...

Showing example in Password


Handling errors​

Every failure from the platform throws K9o\KError. The exception carries these fields that are consistent across every SDK language and every API surface:

FieldTypeDescription
$e->codestringSCREAMING_SNAKE_CASE error code from the closed catalogue
$e->getMessage()stringHuman-readable description; safe to log
$e->contextobjectStructured fields specific to the error family
$e->recommendationstring|nullRemediation hint; null when there is none

Example — handling a credential failure and a tier cap in the same catch block:

PHP
<?php

use K9o\KError;

try {
  $session = $k9o->gate->sign_in(email: '[email protected]', password: '…');
} catch (KError $e) {
  match ($e->code) {
      'K9O_INVALID_CREDENTIALS' =>
          // Wrong email or password — prompt the user to retry.
          handle_bad_credentials($e),
      'K9O_TIER_CAP_HIT' =>
          // Project MAU cap reached — surface upgrade path.
          // $e->recommendation is text when present, otherwise null.
          redirect_to_upgrade($e->recommendation),
      default =>
          log_and_rethrow($e),
  };
}

Showing example in PHP

K9O_INVALID_CREDENTIALS is the auth-family code for a failed email/password sign-in (ch03). K9O_TIER_CAP_HIT is the capacity-family code that fires when a tier-bound cap — for example, monthly active users — is exceeded (ch10); $e->recommendation is a plain string or null.

A catch block that switches on $e->code and falls through to a generic handler for unknown codes is the correct pattern: the platform adds new codes only in new SDK releases, so falling through to a generic handler is safer than silently swallowing an unrecognised code.


Realtime subscriptions​

The PHP SDK delivers realtime events through a Generator. Iterate with foreach — the loop yields one event per frame:

PHP
<?php

use K9o\RealtimeTopic;

foreach ($k9o->realtime->subscribe(RealtimeTopic::collection('orders')) as $event) {
  echo $event['eventType'], ' ', json_encode($event['payload']), PHP_EOL;  // e.g. row_inserted
  if ($event['eventType'] === 'row_deleted') {
      break; // leaving the loop closes the feed
  }
}
Output · bash
row_inserted {"id":"order-124","total":42}
row_deleted {"id":"order-124"}

Showing example in PHP

The wire transport is SSE; the SDK abstracts it into a Generator. A stream lasts up to 300 seconds; to continue after it ends, reconnect with the last event id as Last-Event-ID and drop duplicates by eventId (the client contract, see the Realtime API reference); there is no initial-state replay, so read the current rows first. Long-lived scripts should run the subscription loop in a separate process or use an async PHP runtime (e.g. ReactPHP, Revolt). For topics and the frame format, see the Realtime API reference.

Streams​

Streams are ordered and replayable. max_bytes is at least 10485760 (10 MiB), and the stream's slug (derived from the display name) is what the other calls take. subscribe is a Generator that reconnects from the last sequence when the server closes the connection; it never ends on its own, so stop it with break.

PHP
<?php

$stream = $k9o->streams->create('orders', max_bytes: 10_485_760)->data;
$slug = $stream['slug'];
$k9o->streams->publish($slug, ['id' => 1, 'total' => 42], subject: 'eu.new');
$k9o->streams->publish($slug, ['id' => 2, 'total' => 17]);

foreach ($k9o->streams->subscribe($slug, from_sequence: 0) as $event) {
  echo $event['sequence'], ' ', json_encode($event['data']), "\n"; // 1 {"id":1,"total":42}
  if ((string) $event['sequence'] === '2') {
      break;
  }
}

$page = $k9o->streams->replay($slug, from_sequence: 0, limit: 10)->data;
echo count($page['events']), ' ', var_export($page['hasMore'], true), "\n";
Output · bash
1 {"id":1,"total":42}
2 {"id":2,"total":17}
2 false

Showing example in PHP


See also​

  • API reference — full method signatures, parameters, and return shapes for every surface
  • Conventions — response envelope, KError shape, URL grammar, pagination
  • CLI — the k9o command-line tool uses the same wire contract
  • SDKs — TypeScript, Python, Go, Rust, and all other supported languages