---
title: 'Architecture Overview'
url: 'http://phramecms.org/docs/architecture'
markdown_url: 'http://phramecms.org/docs/architecture.md'
bundle: guide
section: architecture
summary: "Understand PhrameCMS's AI-first micro-kernel design, topological module DAG, 10 official modules, OperationBus pipeline, and hexagonal PSR boundaries."
source: 'https://github.com/PhrameCMS/docs/blob/main/guides/architecture.md'
updated_at: '2026-12-04T21:49:38+00:00'
---

# Architecture Overview

PhrameCMS is an AI-first, API-native, modular PHP 8.5 CMS built around a minimal micro-kernel (`phramecms/core`) and 10 standalone official Composer modules bundled by the `phramecms/cms` metapackage.

## AI-First Micro-Kernel Design

`phramecms/core` contains **zero CMS business logic** — no database driver, no HTTP router, no content entity model, and no template engine. Instead, it provides the primitives every module plugs into:

- **Kernel (`PhrameCms\Core\Kernel`)**: Boots modules in a deterministic two-phase lifecycle (`register(ContainerBuilderInterface $builder)` followed by `boot(ContainerInterface $container)`), exposing an immutable PSR-11 tagged container (`TaggedContainerInterface`).
- **Module Contract (`PhrameCms\Core\Contract\ModuleInterface`)**: Every module declares a unique `name()`, a list of `dependencies()`, a `register()` method for container bindings and service tags, and a `boot()` method for post-build initialization.
- **Deterministic Topological DAG Resolution (`PhrameCms\Core\Module\ModuleResolver`)**: Resolves module boot order via Kahn's algorithm backed by an `SplMinHeap` keyed on registration index. Dependencies always register and boot before dependents, ties preserve original registration order deterministically, missing dependencies throw `MissingDependencyException`, and dependency cycles throw `CircularDependencyException` with the extracted cycle path.
- **PSR-14 Event Bus (`EventDispatcher`, `ListenerProvider`)**: Auto-discovers services tagged `phrame.event_subscriber` (`EventSubscriberInterface::SERVICE_TAG`).
- **Centralized Operation Pipeline (`OperationRegistry`, `OperationBus`)**: Auto-discovers services tagged `phrame.operation` (`OperationRegistry::OPERATION_TAG`) so every transport (HTTP API, MCP, CLI, Admin UI) invokes the exact same validated, authorized, auditable domain logic.

## The 10 Official Modules & Dependency Waves

The `phramecms/cms` metapackage requires `phramecms/core` plus all 10 official modules. Inspecting each module's `dependencies()` yields the exact runtime dependency graph:

```text
Wave 0 — Micro-Kernel
  phramecms/core             (Kernel, DI + tags, PSR-14 events, OperationBus, SchemaValidator)

Wave 1 — Foundation Modules (no hard module dependencies)
  phramecms/database         phrame.database   deps: []
  phramecms/config           phrame.config     deps: []  (optional database storage)
  phramecms/routing          phrame.routing    deps: []

Wave 2 — Domain & Governance Modules
  phramecms/user             phrame.user       deps: [phrame.database]  (optional routing middleware)
  phramecms/entity           phrame.entity     deps: [phrame.database, phrame.config]
  phramecms/proposal         phrame.proposal   deps: [phrame.database]

Wave 3 — Interface & Delivery Adapters
  phramecms/api              phrame.api        deps: [phrame.routing, phrame.entity, phrame.config]
  phramecms/mcp              phrame.mcp        deps: []  (auto-discovers operations, optional routing/user)
  phramecms/cli              phrame.cli        deps: []  (auto-discovers commands & OperationBus)
  phramecms/admin            phrame.admin      deps: [phrame.routing, phrame.user, phrame.entity, phrame.config]
```

| Package | Module Class | Module Name | Declared Dependencies | Responsibility |
| :--- | :--- | :--- | :--- | :--- |
| `phramecms/database` | `DatabaseModule` | `phrame.database` | `[]` | DBAL-backed `ConnectionInterface`, `QueryBuilderInterface`, `SchemaBuilderInterface`, `SchemaInstallRunner`, `InMemoryConnection` |
| `phramecms/config` | `ConfigModule` | `phrame.config` | `[]` | Active config store, canonical JSON `FileConfigStorage`, JSON Schema validation, `ConfigManager`, snapshots, diff & rollback |
| `phramecms/routing` | `RoutingModule` | `phrame.routing` | `[]` | PSR-7/PSR-15 `Router`, `HttpKernel`, `MiddlewarePipeline`, RFC 9457 `ProblemDetailsResponder` |
| `phramecms/user` | `UserModule` | `phrame.user` | `['phrame.database']` | Users, RBAC roles, `RbacPolicyEnforcer`, `AgentTokenManager`, `SessionManager`, `BearerAuthMiddleware`, `SessionAuthMiddleware`, `DatabaseAuditLogger` |
| `phramecms/entity` | `EntityModule` | `phrame.entity` | `['phrame.database', 'phrame.config']` | Dynamic entity types, bundles, Drupal-inspired field storages/instances, revisions, workflow states |
| `phramecms/proposal` | `ProposalModule` | `phrame.proposal` | `['phrame.database']` | AI-first change proposal queue, `ProposalPreviewActor` dry-run staging, optimistic concurrency (`beforeHash`) |
| `phramecms/api` | `ApiModule` | `phrame.api` | `['phrame.routing', 'phrame.entity', 'phrame.config']` | Headless JSON:API content/config/schema endpoints and dynamic OpenAPI 3.1 (`OpenApiGenerator`) |
| `phramecms/mcp` | `McpModule` | `phrame.mcp` | `[]` | Native MCP server (`McpServer`) exposing Operations as tools and `phrame://` state as resources over Stdio and `POST /mcp` |
| `phramecms/cli` | `CliModule` | `phrame.cli` | `[]` | Structured CLI (`CliApplication`) with `--json`, `op:list`, `op:describe`, `op:run`, and module command discovery |
| `phramecms/admin` | `AdminModule` | `phrame.admin` | `['phrame.routing', 'phrame.user', 'phrame.entity', 'phrame.config']` | Server-rendered Twig Admin UI (`/admin`) for content, schema, config, access, appearance, proposals, and audit |

In `phramecms/skeleton`, `App\AppBootstrap::boot()` registers all 10 official modules, `AppModule`, any installed Composer packages declaring `extra.phramecms.modules` (unless `PHRAME_DISCOVER_COMPOSER_MODULES=0`), and project-local modules from `config/modules.php`.

## Centralized `OperationBus` Pipeline

Every transport — JSON:API (`api`), MCP (`mcp`), CLI (`cli`), and Admin UI (`admin`) — is a thin adapter that constructs an `OperationRequest` (`operation`, `input`, `ExecutionContext`) and delegates execution to `PhrameCms\Core\Operation\OperationBus::execute()`.

`OperationBus::execute()` enforces a strict, deterministic **8-step pipeline**:

1. **Resolve Operation**: Look up `OperationInterface` and its `OperationMetadata` from `OperationRegistry` (throws `OperationNotFoundException` if unknown).
2. **Enforce Policy (`PolicyEnforcerInterface::assertAllowed()`)**: Always runs **before** input validation or handler execution so unauthorized callers cannot probe schemas or trigger side effects. Authorization failures immediately emit a failed `AuditRecord` (`stage: authorization`) and throw `AuthorizationException`.
3. **Dry-Run Capability Check**: Rejects requests where `ExecutionContext::$dryRun === true` if `!$metadata->supportsDryRun` with a `ValidationException`.
4. **Input Validation (`SchemaValidatorInterface::validate()`)**: Validates `$request->input` against `$metadata->inputSchema` (JSON Schema). Throws `ValidationException` on mismatch.
5. **Idempotency Lookup (`IdempotencyStoreInterface::get()`)**: For live executions (`!$context->dryRun`) carrying an `idempotencyKey`, checks for a cached `OperationResult` keyed by `(actorId, operation, idempotencyKey)`. On cache hit, logs an `AuditRecord` with `replayed: true` and returns the cached result without re-running the handler.
6. **Execute Handler (`$operation->execute($request->input, $context)`)**: Runs the operation in dry-run preview mode (computing canonical diffs and hashes with zero side effects) or live mode. Handler exceptions emit a failed `AuditRecord` (`stage: execution`) and rethrow.
7. **Store Idempotent Result (`IdempotencyStoreInterface::put()`)**: Persists the `OperationResult` for live executions with an `idempotencyKey`.
8. **Emit Audit Record (`AuditLoggerInterface::record()`)**: Writes an immutable `AuditRecord` capturing `actorId`, `actorType`, `onBehalfOf`, `sessionId`, `operation`, `target`, `dryRun`, `success`, `beforeHash`, `afterHash`, `correlationId`, and metadata.

> **Security default in `Kernel`:** `Kernel::boot()` only binds the dev-only `AllowAllPolicyEnforcer` when `phramecms/user` is **not** installed (`!InstalledVersions::isInstalled('phramecms/user')`). Whenever `phramecms/user` is installed, `UserModule` binds the deny-by-default `RbacPolicyEnforcer` as `PolicyEnforcerInterface` and `DatabaseAuditLogger` as `AuditLoggerInterface`.

## Hexagonal Boundaries & PSR Standards

PhrameCMS keeps domain contracts strictly decoupled from third-party libraries and delivery frameworks:

- **Standard PSR interfaces across module boundaries**:
  - **PSR-11** (`psr/container`) — Dependency injection (`TaggedContainerInterface` extends `Psr\Container\ContainerInterface`)
  - **PSR-14** (`psr/event-dispatcher`) — Domain event dispatching (`EventDispatcherInterface`, `ListenerProviderInterface`)
  - **PSR-20** (`psr/clock`) — Deterministic time via `Psr\Clock\ClockInterface` (`SystemClock` default)
  - **PSR-3** (`psr/log`) — Logging contract in `phramecms/core`
  - **PSR-7 / PSR-15 / PSR-17** (`psr/http-message`, `psr/http-server-handler`, `psr/http-server-middleware`, `psr/http-factory`) — HTTP requests, responses, middleware, and handlers in `routing`, `user`, `api`, `mcp`, and `admin`
- **Isolated vendor adapters**:
  - **Twig (`twig/twig`) is isolated strictly inside `phramecms/admin`**, hidden behind `PhrameCms\Admin\Contract\TemplateRendererInterface` (`TwigTemplateRenderer`). No other module depends on Twig or renders HTML.
  - **Doctrine DBAL** is wrapped strictly inside `phramecms/database` (`DbalConnection`, `DbalQueryBuilder`, `DbalSchemaBuilder`) behind `ConnectionInterface`, `QueryBuilderInterface`, and `SchemaBuilderInterface` — allowing tests and lightweight tooling to swap in `InMemoryConnection` without touching domain code.
- **Transport parity**: Because all business logic lives in `OperationInterface` implementations, adding a new entity type, field, or custom module operation automatically makes it available across JSON:API, OpenAPI 3.1, MCP tools, CLI (`op:list` / `op:describe` / `op:run`), and the Admin UI.

## Related Guides

- [Getting Started](getting-started.md) — Install and run the skeleton locally.
- [Configuration Sync](configuration-sync.md) — Export, diff, import, and roll back Git-tracked configuration.
- [Users, RBAC, and AI Agent Tokens](users-rbac-tokens.md) — How `RbacPolicyEnforcer`, tokens, and audit records work.
- [AI Change Proposals & Human Approval Queue](proposals.md) — How `ProposalModule` layers human approval onto `OperationBus`.
