PHP SDK Guide

phramecms/php-sdk is the official, framework-agnostic PHP 8.5 client for consuming a PhrameCMS instance over HTTP. It wraps the JSON:API Content API (/api/v1/content/*), Configuration API (/api/v1/config/*), and Schema/OpenAPI API (/api/v1/schema/*, /api/v1/openapi.json) behind strongly typed readonly DTOs, a fluent query builder, RFC 9457 Problem Details exceptions, an optional Symfony Bundle (PhrameCmsBundle), and an in-memory FakePhrameClient for unit testing.

For exhaustive method signatures, DTO property tables, exception mappings, and bundle service IDs, see the PHP SDK Reference.


1. Installation

phramecms/php-sdk depends only on PSR interfaces (psr/http-client, psr/http-factory, psr/http-message). Install it alongside your preferred PSR-18 HTTP client and PSR-17 factories (for example symfony/http-client + nyholm/psr7, or guzzlehttp/guzzle):

bash
composer require phramecms/php-sdk symfony/http-client nyholm/psr7

2. Symfony Integration (PhrameCmsBundle)

When using Symfony (symfony/framework-bundle + symfony/http-client), phramecms/php-sdk ships an optional bundle (PhrameCms\Sdk\Symfony\PhrameCmsBundle) that registers and autowires all SDK interfaces and concrete clients. Core SDK files contain zero references to Symfony, so Symfony remains strictly optional.

Register the Bundle

Add PhrameCmsBundle to config/bundles.php:

php
<?php

return [
    Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
    PhrameCms\Sdk\Symfony\PhrameCmsBundle::class => ['all' => true],
];

Configure config/packages/phrame_cms.yaml

yaml
phrame_cms:
    base_uri: '%env(PHRAME_API_BASE_URL)%'
    token: '%env(default::PHRAME_API_TOKEN)%'
    # Optional custom User-Agent (defaults to "phramecms-php-sdk/0.1")
    user_agent: 'my-headless-site/1.0'
    # Optional custom PSR-18 Psr\Http\Client\ClientInterface service ID
    # http_client: 'app.custom_psr18_client'

Set the environment variables in .env.local (never commit real tokens):

dotenv
PHRAME_API_BASE_URL=https://cms.example.test
PHRAME_API_TOKEN=<agent-token>

Inject via Constructor Autowiring

PhrameCmsBundle aliases PhrameClientInterface, ContentClientInterface, ConfigClientInterface, SchemaClientInterface, HttpTransportInterface, and ClientConfig for type-hinted autowiring:

php
<?php

declare(strict_types=1);

namespace App\Content;

use PhrameCms\Sdk\Contract\PhrameClientInterface;
use PhrameCms\Sdk\Query\ContentQuery;

final readonly class BlogService
{
    public function __construct(
        private PhrameClientInterface $phrame,
    ) {}

    /** @return list<array{id: string, title: string, slug: string}> */
    public function recentPublishedPosts(int $limit = 10): array
    {
        $query = ContentQuery::create()
            ->filter('state', 'published')
            ->sort('-createdAt')
            ->limit($limit);

        $collection = $this->phrame->content()->list('content', 'article', $query);

        $posts = [];
        foreach ($collection->items as $item) {
            $posts[] = [
                'id' => $item->id,
                'title' => $item->string('title'),
                'slug' => $item->string('slug'),
            ];
        }

        return $posts;
    }
}

For a complete cached Symfony 8 frontend walkthrough, see the Headless Symfony App with PHP SDK recipe.


3. Framework-Agnostic Setup (PSR-18 / PSR-17)

Outside Symfony — in vanilla PHP, Laravel, Slim, Mezzio, or CLI workers — construct a client via PhrameClient::create() using any PSR-18 Psr\Http\Client\ClientInterface and PSR-17 RequestFactoryInterface + StreamFactoryInterface.

With symfony/http-client + nyholm/psr7

php
<?php

declare(strict_types=1);

use Nyholm\Psr7\Factory\Psr17Factory;
use PhrameCms\Sdk\ClientConfig;
use PhrameCms\Sdk\PhrameClient;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\Psr18Client;

$psr17 = new Psr17Factory();
$psr18 = new Psr18Client(HttpClient::create(['timeout' => 10.0]), $psr17, $psr17);

$client = PhrameClient::create(
    config: new ClientConfig(
        baseUri: 'https://cms.example.test',
        token: $_ENV['PHRAME_API_TOKEN'] ?? null,
        userAgent: 'acme-sync-worker/1.0',
        correlationIdProvider: static fn(): string => 'req-' . bin2hex(random_bytes(8)),
    ),
    httpClient: $psr18,
    requestFactory: $psr17,
    streamFactory: $psr17,
);

With Guzzle (guzzlehttp/guzzle + guzzlehttp/psr7)

GuzzleHttp\Client implements PSR-18 ClientInterface, and GuzzleHttp\Psr7\HttpFactory implements both PSR-17 RequestFactoryInterface and StreamFactoryInterface:

php
<?php

declare(strict_types=1);

use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Psr7\HttpFactory;
use PhrameCms\Sdk\ClientConfig;
use PhrameCms\Sdk\PhrameClient;

$httpFactory = new HttpFactory();

$client = PhrameClient::create(
    config: new ClientConfig(
        baseUri: 'https://cms.example.test',
        token: '<agent-token>',
    ),
    httpClient: new GuzzleClient(['timeout' => 10.0]),
    requestFactory: $httpFactory,
    streamFactory: $httpFactory,
);

Laravel Service Provider Example

Bind PhrameClientInterface as a singleton in AppServiceProvider::register() so controllers, jobs, and Artisan commands can type-hint it (and swap it for FakePhrameClient in tests):

php
$this->app->singleton(PhrameClientInterface::class, function (): PhrameClientInterface {
    $httpFactory = new \GuzzleHttp\Psr7\HttpFactory();

    return PhrameClient::create(
        config: new ClientConfig(
            baseUri: (string) config('services.phrame.base_uri'),
            token: config('services.phrame.token'),
        ),
        httpClient: new \GuzzleHttp\Client(['timeout' => 10.0]),
        requestFactory: $httpFactory,
        streamFactory: $httpFactory,
    );
});

4. Querying & Mutating Content ($client->content())

Fluent ContentQuery

PhrameCms\Sdk\Query\ContentQuery is an immutable, fluent builder that serializes into PhrameCMS JSON:API query parameters (filter[...], sort, page[limit], page[offset], fields[...], include):

php
<?php

declare(strict_types=1);

use PhrameCms\Sdk\Query\ContentQuery;

$query = ContentQuery::create()
    ->filter('state', 'published')
    ->filter('weight', ['gte' => 10])
    ->sort('weight')
    ->sort('createdAt', descending: true) // or ->sort('-createdAt')
    ->sparseFields('content--article', ['title', 'slug', 'summary', 'state'])
    ->include('author')
    ->limit(25)
    ->offset(0);

$collection = $client->content()->list('content', 'article', $query);

foreach ($collection->items as $article) {
    $title = $article->string('title');
    $summary = $article->nullableString('summary');
    $state = $article->state();
}

When using ->include('author'), resolve included resources from $collection->included with $collection->findIncluded('content--author', $authorId).

Automatic Pagination (iterateAll()) & Single Lookup (findOneBy())

To walk an entire collection across pages without manually tracking page[offset], use iterateAll() (returns a lazy Generator<int, ResourceObject>):

php
$query = ContentQuery::create()
    ->filter('state', 'published')
    ->sort('weight')
    ->limit(100); // page size per HTTP request

foreach ($client->content()->iterateAll('content', 'doc', $query) as $doc) {
    echo $doc->string('slug') . "\n";
}

To fetch a single matching entity by field filters (for example, looking up an article by slug) without throwing on empty results, use findOneBy():

php
$article = $client->content()->findOneBy('content', 'article', [
    'slug' => 'hello-phramecms',
    'state' => 'published',
]);

if ($article === null) {
    // Handle 404 in your frontend
}

For direct lookup by entity ID, call $client->content()->get('content', 'article', $id) (throws NotFoundException on HTTP 404).

Creating, Updating, Transitioning, Deleting & Revisions

All write methods support dryRun: true (sends ?dry_run=true) and idempotencyKey (sends the Idempotency-Key header) and return a readonly MutationResult:

php
// 1. Dry-run preview before creating
$preview = $client->content()->create(
    entityType: 'content',
    bundle: 'article',
    fields: ['title' => 'Release 0.1', 'slug' => 'release-0-1'],
    state: 'draft',
    logMessage: 'Initial draft',
    dryRun: true,
);
// $preview->dryRun === true; inspect $preview->diff

// 2. Live create with idempotency key
$created = $client->content()->create(
    entityType: 'content',
    bundle: 'article',
    fields: ['title' => 'Release 0.1', 'slug' => 'release-0-1'],
    state: 'draft',
    logMessage: 'Initial draft',
    idempotencyKey: 'article-release-0-1',
);

$entityId = $created->resource?->id;

// 3. Partial update (PATCH)
$client->content()->update(
    entityType: 'content',
    bundle: 'article',
    id: (string) $entityId,
    fields: ['title' => 'PhrameCMS 0.1 Released'],
    logMessage: 'Polish headline',
);

// 4. Workflow state transition (requires entity.content.article.publish for "published")
$client->content()->transition(
    entityType: 'content',
    bundle: 'article',
    id: (string) $entityId,
    targetState: 'published',
    logMessage: 'Approve and publish',
);

// 5. Inspect immutable revision history
$revisions = $client->content()->revisions('content', 'article', (string) $entityId);
foreach ($revisions as $rev) {
    // $rev->revisionId, $rev->state, $rev->logMessage, $rev->actorId, $rev->createdAt
}

// 6. Delete (supports dryRun and idempotencyKey)
$client->content()->delete('content', 'article', (string) $entityId);

5. Configuration & Schema / OpenAPI Clients

Config Client ($client->configs())

Read, diff, and update PhrameCMS configuration objects (requires config.read / config.<name>.read and config.write / config.<name>.write scopes):

php
// List configuration summaries matching a prefix
$summaries = $client->configs()->list(prefix: 'admin.');

// Fetch a single configuration document (includes SHA-256 content hash)
$settings = $client->configs()->get('admin.settings');
$brandName = $settings->data['brand_name'] ?? 'PhrameCMS';

// Preview or write an update
$mutation = $client->configs()->set(
    name: 'admin.settings',
    data: ['brand_name' => 'Acme CMS', 'theme' => 'default'],
    reason: 'Rebrand admin header',
    dryRun: true,
);

// Compute drift against the server's sync directory or a snapshot
$diff = $client->configs()->diff(prefix: 'entity.');
if (!$diff->empty) {
    foreach ($diff->updated as $change) {
        // $change->name, $change->before, $change->after
    }
}

Schema & OpenAPI Client ($client->schemas())

Introspect compiled bundle JSON Schemas (requires schema.read) or fetch the public OpenAPI 3.1 document (GET /api/v1/openapi.json — works even when token is null):

php
// Fetch all compiled bundle schemas, or narrow to one entity type / bundle
$allSchemas = $client->schemas()->index();
$contentSchemas = $client->schemas()->entityType('content');
$articleSchema = $client->schemas()->bundle('content', 'article');

// Raw JSON Schema draft 2020-12 array for the bundle's fields
$properties = $articleSchema->schema['properties'] ?? [];

// Fetch the dynamically generated OpenAPI 3.1 specification
$openApiSpec = $client->schemas()->openApi();

6. RFC 9457 Error Handling

Every non-2xx HTTP response is parsed into a PhrameCms\Sdk\Problem\ProblemDetails object and thrown as a typed exception implementing PhrameCms\Sdk\Exception\PhrameException:

php
<?php

declare(strict_types=1);

use PhrameCms\Sdk\Exception\ApiException;
use PhrameCms\Sdk\Exception\AuthenticationException;
use PhrameCms\Sdk\Exception\AuthorizationException;
use PhrameCms\Sdk\Exception\ConflictException;
use PhrameCms\Sdk\Exception\NotFoundException;
use PhrameCms\Sdk\Exception\TransportException;
use PhrameCms\Sdk\Exception\ValidationException;

try {
    $result = $client->content()->update('content', 'article', $id, $fields);
} catch (ValidationException $e) {
    // HTTP 422 — inspect structured per-field issues
    foreach ($e->issues() as $issue) {
        // $issue->path (e.g. "/fields/title"), $issue->message, $issue->rule
    }
} catch (NotFoundException $e) {
    // HTTP 404 — entity or bundle not found
} catch (AuthenticationException $e) {
    // HTTP 401 — missing, invalid, expired, or revoked Bearer token
} catch (AuthorizationException $e) {
    // HTTP 403 — token lacks the required permission scope
} catch (ConflictException $e) {
    // HTTP 409 — referential integrity or state conflict
} catch (ApiException $e) {
    // Any other non-2xx HTTP status (400, 429, 500, 503, ...)
    $correlationId = $e->correlationId();
    $problem = $e->problem();
} catch (TransportException $e) {
    // Network failure, timeout, invalid JSON body, or schema shape mismatch
}

HttpTransport preserves X-Correlation-Id from the server response (or falls back to the value produced by ClientConfig::$correlationIdProvider), making it easy to correlate client errors with PhrameCMS audit and server logs.


7. Unit Testing with FakePhrameClient

Always type-hint PhrameClientInterface (or ContentClientInterface, ConfigClientInterface, SchemaClientInterface) in your application services. In PHPUnit tests, pass PhrameCms\Sdk\Testing\FakePhrameClient — an in-memory fake with full filtering, sorting, pagination, sparse fieldsets, include resolution, revision recording, config diffing, and mutation inspection, requiring zero HTTP calls:

php
<?php

declare(strict_types=1);

use PhrameCms\Sdk\Model\BundleSchema;
use PhrameCms\Sdk\Model\ResourceObject;
use PhrameCms\Sdk\Testing\FakePhrameClient;
use PHPUnit\Framework\TestCase;

final class BlogServiceTest extends TestCase
{
    public function testListsOnlyPublishedPostsSortedNewestFirst(): void
    {
        $fake = (new FakePhrameClient())
            ->withResources(
                new ResourceObject(
                    type: 'content--article',
                    id: 'art-1',
                    attributes: [
                        'title' => 'Draft Post',
                        'slug' => 'draft-post',
                        'state' => 'draft',
                        'createdAt' => '2026-05-02T10:00:00Z',
                    ],
                ),
                new ResourceObject(
                    type: 'content--article',
                    id: 'art-2',
                    attributes: [
                        'title' => 'Published Post',
                        'slug' => 'published-post',
                        'state' => 'published',
                        'createdAt' => '2026-05-01T10:00:00Z',
                    ],
                ),
            )
            ->withConfig('admin.settings', ['brand_name' => 'Test Site'])
            ->withSchema(new BundleSchema(
                id: 'content--article',
                entityType: 'content',
                bundle: 'article',
                schema: ['type' => 'object', 'properties' => ['title' => ['type' => 'string']]],
            ));

        $service = new \App\Content\BlogService($fake);
        $posts = $service->recentPublishedPosts();

        self::assertCount(1, $posts);
        self::assertSame('published-post', $posts[0]['slug']);
    }

    public function testRecordsLiveMutationsOnly(): void
    {
        $fake = new FakePhrameClient();

        // Dry-run does not persist or record a mutation
        $fake->content()->create('content', 'article', ['title' => 'Preview'], dryRun: true);
        self::assertSame([], $fake->recordedMutations());

        // Live create persists and records the mutation
        $fake->content()->create('content', 'article', ['title' => 'Live'], idempotencyKey: 'k-1');
        self::assertCount(1, $fake->recordedMutations());
        self::assertSame('content.create', $fake->recordedMutations()[0]['operation']);
        self::assertSame('k-1', $fake->recordedMutations()[0]['idempotencyKey']);
    }
}