phramecms / php-sdk
Framework-agnostic PHP 8.5 PSR-18/PSR-17 SDK for the PhrameCMS Content, Config, and Schema APIs.
Requires
- php: ^8.5
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- infection/infection: ^0.35.12
- nyholm/psr7: ^1.8
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^13.0
- spaze/phpstan-disallowed-calls: ^4.15
- symfony/config: ^8.0
- symfony/dependency-injection: ^8.0
- symfony/framework-bundle: ^8.0
- symfony/http-client: ^8.0
- symfony/http-kernel: ^8.0
- symfony/yaml: ^8.0
Suggests
- nyholm/psr7: Lightweight PSR-7/PSR-17 HTTP message and factory implementation
- symfony/framework-bundle: For optional Symfony integration via PhrameCmsBundle
- symfony/http-client: PSR-18 HTTP client implementation
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-04 21:35:05 UTC
README
Official, framework-agnostic PHP 8.5 client SDK for the PhrameCMS HTTP API (phramecms/api).
- Zero framework lock-in — core runtime dependencies are strictly
php: ^8.5,psr/http-client: ^1.0,psr/http-factory: ^1.0, andpsr/http-message: ^2.0. - Typed JSON:API & OpenAPI clients — fluent
ContentQuerybuilder, immutablefinal readonlyDTOs for Content, Config, and Schema/OpenAPI APIs. - RFC 9457 Problem Details — automatic status-to-exception mapping (
401/403/404/409/422/other4xx/5xx) withX-Correlation-Idtracking and structured422validation issues. - Safe mutations — first-class support for
dryRun: truepreviews andIdempotency-Keyheaders. - Built-in testing fakes —
FakePhrameClientfor fast, offline unit tests with zero HTTP mocking boilerplate. - Optional Symfony integration — drop-in
PhrameCmsBundlefor Symfony 8+ apps with full interface autowiring.
Requirements
- PHP
^8.5 - Any PSR-18 HTTP client (
psr/http-client-implementation) and PSR-17 HTTP factory (psr/http-factory-implementation), such as:symfony/http-client+nyholm/psr7guzzlehttp/guzzle
Installation
Packagist / Standard Composer
composer require phramecms/php-sdk
If your application does not already provide PSR-18 / PSR-17 implementations, install one alongside the SDK — for example:
# Option A: Symfony HttpClient + Nyholm PSR-7/17 composer require symfony/http-client nyholm/psr7 # Option B: Guzzle (provides both PSR-18 and PSR-17) composer require guzzlehttp/guzzle
Symfony Integration (PhrameCmsBundle)
For Symfony applications, install symfony/framework-bundle and symfony/http-client (both are listed under suggest, keeping the core SDK completely framework-agnostic).
1. Register the Bundle
Add PhrameCmsBundle to config/bundles.php:
<?php declare(strict_types=1); return [ Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true], PhrameCms\Sdk\Symfony\PhrameCmsBundle::class => ['all' => true], ];
2. Configure config/packages/phrame_cms.yaml
phrame_cms: base_uri: '%env(PHRAME_API_BASE_URI)%' token: '%env(default::PHRAME_API_TOKEN)%' # Optional; defaults to null http_client: null # Optional PSR-18 service ID; defaults to Symfony's http_client wrapped in Psr18Client user_agent: 'my-symfony-app/1.0' # Optional; defaults to "phramecms-php-sdk/0.1"
3. Autowire SDK Clients
PhrameCmsBundle registers and aliases the SDK interfaces (and concrete classes) for autowiring:
PhrameCms\Sdk\Contract\PhrameClientInterfacePhrameCms\Sdk\Contract\ContentClientInterfacePhrameCms\Sdk\Contract\ConfigClientInterfacePhrameCms\Sdk\Contract\SchemaClientInterfacePhrameCms\Sdk\Contract\HttpTransportInterfacePhrameCms\Sdk\ClientConfig
<?php declare(strict_types=1); namespace App\Controller; use PhrameCms\Sdk\Contract\ContentClientInterface; use PhrameCms\Sdk\Contract\PhrameClientInterface; use PhrameCms\Sdk\Query\ContentQuery; use Symfony\Component\HttpFoundation\JsonResponse; final readonly class ArticleController { public function __construct( private ContentClientInterface $content, private PhrameClientInterface $phrame, ) {} public function index(): JsonResponse { $collection = $this->content->list( entityType: 'node', bundle: 'article', query: ContentQuery::create() ->filter('state', 'published') ->sort('-createdAt') ->limit(10), ); $site = $this->phrame->configs()->get('site.settings'); return new JsonResponse([ 'site' => $site->data['name'] ?? 'PhrameCMS', 'total' => $collection->meta->total, 'articles' => array_map( static fn($item): array => [ 'id' => $item->id, 'title' => $item->string('title'), 'slug' => $item->string('slug'), ], $collection->items, ), ]); } }
Framework-Agnostic Setup (PhrameClient::create())
Outside Symfony — in Laravel, Slim, Mezzio, or vanilla PHP — instantiate PhrameClient directly using PhrameClient::create() with any PSR-18 client and PSR-17 factories.
Option A: symfony/http-client + nyholm/psr7
<?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; $psr17Factory = new Psr17Factory(); $psr18Client = new Psr18Client( HttpClient::create(['timeout' => 10.0]), $psr17Factory, $psr17Factory, ); $config = new ClientConfig( baseUri: 'https://cms.example.com', token: getenv('PHRAME_API_TOKEN') ?: null, userAgent: 'my-php-app/1.0', correlationIdProvider: static fn(): string => bin2hex(random_bytes(16)), ); $client = PhrameClient::create( config: $config, httpClient: $psr18Client, requestFactory: $psr17Factory, streamFactory: $psr17Factory, );
Option B: guzzlehttp/guzzle
<?php declare(strict_types=1); use GuzzleHttp\Client; use GuzzleHttp\Psr7\HttpFactory; use PhrameCms\Sdk\ClientConfig; use PhrameCms\Sdk\PhrameClient; $guzzle = new Client([ 'timeout' => 10.0, 'http_errors' => false, // Let PhrameCMS SDK map 4xx/5xx RFC 9457 Problem Details ]); $httpFactory = new HttpFactory(); $client = PhrameClient::create( config: new ClientConfig( baseUri: 'https://cms.example.com', token: getenv('PHRAME_API_TOKEN') ?: null, ), httpClient: $guzzle, requestFactory: $httpFactory, streamFactory: $httpFactory, );
Note for Guzzle users: Set
'http_errors' => falseonGuzzleHttp\Clientso non-2xx responses are returned to the SDK'sHttpTransportand decoded into typed RFC 9457 exceptions (AuthenticationException,ValidationException, etc.) rather than throwing Guzzle's generic client exceptions.
In Laravel or Slim, bind PhrameClientInterface (plus ContentClientInterface, ConfigClientInterface, and SchemaClientInterface via $client->content(), $client->configs(), and $client->schemas()) as singletons in your service provider or DI container using either snippet above.
Content API & ContentQuery
ContentQuery is an immutable, fluent builder for JSON:API query parameters (filter[...], sort, page[limit], page[offset], fields[...], include).
Listing, Filtering, Sorting, Sparse Fieldsets & Includes
<?php declare(strict_types=1); use PhrameCms\Sdk\Query\ContentQuery; $query = ContentQuery::create() ->filter('state', 'published') ->filters([ 'featured' => true, 'reading_time' => ['gte' => 3], ]) ->sort('-createdAt') ->sort('title') ->sparseFields('node--article', ['title', 'slug', 'reading_time', 'state', 'createdAt']) ->include('author', 'tags') ->limit(25) ->offset(0); $collection = $client->content()->list('node', 'article', $query); foreach ($collection->items as $article) { $title = $article->string('title'); $summary = $article->nullableString('summary'); $readingTime = $article->int('reading_time'); $state = $article->state(); // Resolve included relationships via findIncluded() $authorPointer = $article->relationships['author']['data'] ?? null; $author = is_array($authorPointer) ? $collection->findIncluded((string) $authorPointer['type'], (string) $authorPointer['id']) : null; $authorName = $author?->string('display_name') ?? 'Unknown'; } // Pagination metadata and links $total = $collection->meta->total; $nextLink = $collection->links->next;
Auto-Paginating Across All Pages (iterateAll)
iterateAll() returns a lazy Generator<int, ResourceObject> that transparently advances page[offset] until all matching records have been yielded:
<?php declare(strict_types=1); use PhrameCms\Sdk\Query\ContentQuery; $query = ContentQuery::create() ->filter('state', 'published') ->sort('createdAt') ->limit(50); foreach ($client->content()->iterateAll('node', 'article', $query) as $article) { echo $article->id . ': ' . $article->string('title') . PHP_EOL; }
Fetching Single Records & Revisions (get, findOneBy, revisions)
<?php declare(strict_types=1); use PhrameCms\Sdk\Query\ContentQuery; // Fetch a single entity by ID $article = $client->content()->get( entityType: 'node', bundle: 'article', id: 'art_03', query: ContentQuery::create()->include('author'), ); // Find the first matching entity by filter map (returns ?ResourceObject) $bySlug = $client->content()->findOneBy( entityType: 'node', bundle: 'article', filters: ['slug' => 'headless-php-with-phramecms', 'state' => 'published'], ); // List immutable revision history (list<RevisionRecord>) $revisions = $client->content()->revisions('node', 'article', 'art_03'); foreach ($revisions as $revision) { echo sprintf( "%s (%s) by %s [%s]: %s\n", $revision->revisionId, $revision->state, $revision->actorId, $revision->createdAt, $revision->logMessage, ); }
Content Mutations with dryRun and idempotencyKey
All mutating operations (create, update, delete, transition) return a MutationResult containing $result->resource, $result->dryRun, $result->diff, and $result->meta:
<?php declare(strict_types=1); // 1. Preview creation with dryRun: true (no state is persisted) $preview = $client->content()->create( entityType: 'node', bundle: 'article', fields: [ 'title' => 'Release Notes 0.2', 'slug' => 'release-notes-0-2', ], state: 'draft', dryRun: true, ); // Inspect $preview->dryRun (true) and $preview->diff // 2. Persist with an Idempotency-Key header for safe retries $created = $client->content()->create( entityType: 'node', bundle: 'article', fields: [ 'title' => 'Release Notes 0.2', 'slug' => 'release-notes-0-2', ], state: 'draft', logMessage: 'Initial draft', idempotencyKey: 'article-create-release-0-2', ); $entityId = $created->resource->id; // 3. Partial update (PATCH) $updated = $client->content()->update( entityType: 'node', bundle: 'article', id: $entityId, fields: ['title' => 'PhrameCMS 0.2 Release Notes'], logMessage: 'Refine title', idempotencyKey: 'article-update-release-0-2', ); // 4. Workflow state transition $published = $client->content()->transition( entityType: 'node', bundle: 'article', id: $entityId, targetState: 'published', logMessage: 'Publish release notes', idempotencyKey: 'article-publish-release-0-2', ); // 5. Delete (supports dryRun and idempotencyKey) $deleted = $client->content()->delete( entityType: 'node', bundle: 'article', id: $entityId, dryRun: false, idempotencyKey: 'article-delete-release-0-2', );
Config API
Use $client->configs() (ConfigClientInterface) to inspect, modify, and diff active configuration:
<?php declare(strict_types=1); // List all configuration names, optionally filtered by prefix $summaries = $client->configs()->list(prefix: 'site.'); foreach ($summaries as $summary) { echo $summary->name . PHP_EOL; } // Read a configuration document $settings = $client->configs()->get('site.settings'); $siteName = $settings->data['name'] ?? ''; $contentHash = $settings->hash; // Preview a configuration update with dryRun: true $preview = $client->configs()->set( name: 'site.settings', data: ['name' => 'PhrameCMS Portal', 'locale' => 'en'], reason: 'Update site title', dryRun: true, ); // Apply the update with an idempotency key $applied = $client->configs()->set( name: 'site.settings', data: ['name' => 'PhrameCMS Portal', 'locale' => 'en'], reason: 'Update site title', idempotencyKey: 'config-site-settings-v2', ); // Compute a configuration diff (against sync storage, a snapshot, or a directory) $diff = $client->configs()->diff(prefix: 'site.', snapshotId: $applied->snapshotId); if (!$diff->empty) { foreach ($diff->updated as $change) { // Each ConfigChange exposes $change->name, $change->before, $change->after echo 'Updated: ' . $change->name . PHP_EOL; } } // Delete a configuration entry $deleted = $client->configs()->delete( name: 'site.legacy_banner', reason: 'Remove deprecated banner config', dryRun: false, idempotencyKey: 'config-delete-legacy-banner', );
Schema & OpenAPI Discovery
Use $client->schemas() (SchemaClientInterface) to fetch compiled JSON Schema 2020-12 bundle definitions and the live OpenAPI 3.1 document:
<?php declare(strict_types=1); // List all compiled bundle schemas across all entity types $allSchemas = $client->schemas()->index(); // List compiled bundle schemas for a single entity type $nodeSchemas = $client->schemas()->entityType('node'); // Fetch a single bundle schema $articleSchema = $client->schemas()->bundle('node', 'article'); $jsonSchema = $articleSchema->schema; // JSON Schema 2020-12 associative array // Fetch the live OpenAPI 3.1 specification (GET /api/v1/openapi.json) $openApiSpec = $client->schemas()->openApi(); $openApiVersion = $openApiSpec['openapi']; // e.g. "3.1.0"
Error Handling (RFC 9457 Problem Details)
All SDK exceptions implement PhrameCms\Sdk\Exception\PhrameException. Non-2xx API responses are parsed as RFC 9457 application/problem+json into ProblemDetails and mapped to dedicated exception classes:
| HTTP Status | Exception Class | Notes |
|---|---|---|
401 |
AuthenticationException |
Missing, invalid, or expired Bearer token |
403 |
AuthorizationException |
Authenticated actor lacks required permission |
404 |
NotFoundException |
Entity, config, bundle, or route not found |
409 |
ConflictException |
Duplicate ID or schema/resource conflict |
422 |
ValidationException |
Schema/payload errors via $e->issues() (list<ValidationIssue>) |
Other 4xx / 5xx |
ApiException |
Base class for all HTTP API error responses |
| Network / JSON errors | TransportException |
PSR-18 client failures or malformed JSON payloads |
Every ApiException exposes $e->statusCode(), $e->problem(), and $e->correlationId() (populated from X-Correlation-Id for log tracing):
<?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\PhrameException; use PhrameCms\Sdk\Exception\TransportException; use PhrameCms\Sdk\Exception\ValidationException; try { $client->content()->create('node', 'article', ['slug' => 'INVALID SLUG']); } catch (ValidationException $e) { // Structured field-level issues from RFC 9457 "errors" extension foreach ($e->issues() as $issue) { echo sprintf("[%s] %s (%s)\n", $issue->path, $issue->message, $issue->rule ?? 'validation'); } echo 'Correlation ID: ' . ($e->correlationId() ?? 'n/a') . PHP_EOL; } catch (AuthenticationException $e) { // 401 — refresh or verify PHRAME_API_TOKEN } catch (AuthorizationException $e) { // 403 — insufficient RBAC permissions } catch (NotFoundException $e) { // 404 — entity type, bundle, or ID does not exist } catch (ConflictException $e) { // 409 — duplicate ID or conflicting state } catch (ApiException $e) { // Other 4xx / 5xx API errors (e.g. 500 Internal Server Error) error_log(sprintf( 'PhrameCMS error %d (%s): %s [correlation=%s]', $e->statusCode(), $e->problem()->title, $e->problem()->detail ?? 'no detail', $e->correlationId() ?? 'none', )); } catch (TransportException $e) { // Connection timeout, DNS error, or invalid JSON response } catch (PhrameException $e) { // Catch-all for any SDK exception }
Unit Testing with FakePhrameClient
Type-hint your application services against PhrameClientInterface, ContentClientInterface, ConfigClientInterface, or SchemaClientInterface, and inject FakePhrameClient in unit tests — no HTTP mocks or network calls required:
<?php declare(strict_types=1); use PhrameCms\Sdk\Model\BundleSchema; use PhrameCms\Sdk\Model\ResourceObject; use PhrameCms\Sdk\Testing\FakePhrameClient; $fake = (new FakePhrameClient()) ->withResource(new ResourceObject( type: 'node--article', id: 'art_1', attributes: ['title' => 'Hello PhrameCMS', 'slug' => 'hello-phramecms', 'state' => 'published'], )) ->withConfig('site.settings', ['name' => 'Test Site', 'locale' => 'en']) ->withSchema(new BundleSchema( id: 'node.article', entityType: 'node', bundle: 'article', schema: ['type' => 'object', 'required' => ['title', 'slug']], )) ->withOpenApi(['openapi' => '3.1.0', 'info' => ['title' => 'Test API', 'version' => '0.1.0']]); // Run your service against $fake, then assert recorded mutations $fake->content()->update('node', 'article', 'art_1', ['title' => 'Updated Title'], idempotencyKey: 'k-1'); $mutations = $fake->recordedMutations(); // $mutations[0]['operation'] === 'content.update' // $mutations[0]['idempotencyKey'] === 'k-1'
FakePhrameClient supports filtering, sorting, pagination, sparse fieldsets, relationship includes, dryRun: true previews (without mutating in-memory state or recording mutations), revision tracking, config diffs, and clearRecordedMutations().
Local Quality Checks
Run the full validation and quality suite locally (PHP syntax lint, PHPStan at level max with disallowed-calls rules, PHP-CS-Fixer @PER-CS strict check, and PHPUnit):
composer validate --strict --no-check-publish && composer check
Individual scripts:
composer lint— PHP syntax check (php -l) acrosssrc/andtests/composer stan— PHPStan levelmaxstatic analysiscomposer cs:check— PHP-CS-Fixer dry-run check (composer cs:fixto auto-fix)composer test— PHPUnit test suite (including golden JSON:API & RFC 9457 contract tests undertests/Contract/)