Architecture
Architecture Overview
Understand PhrameCMS's AI-first micro-kernel design, topological module DAG, 10 official modules, OperationBus pipeline, and hexagonal PSR boundaries.
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 byboot(ContainerInterface $container)), exposing an immutable PSR-11 tagged container (TaggedContainerInterface). - Module Contract (
PhrameCms\Core\Contract\ModuleInterface): Every module declares a uniquename(), a list ofdependencies(), aregister()method for container bindings and service tags, and aboot()method for post-build initialization. - Deterministic Topological DAG Resolution (
PhrameCms\Core\Module\ModuleResolver): Resolves module boot order via Kahn's algorithm backed by anSplMinHeapkeyed on registration index. Dependencies always register and boot before dependents, ties preserve original registration order deterministically, missing dependencies throwMissingDependencyException, and dependency cycles throwCircularDependencyExceptionwith the extracted cycle path. - PSR-14 Event Bus (
EventDispatcher,ListenerProvider): Auto-discovers services taggedphrame.event_subscriber(EventSubscriberInterface::SERVICE_TAG). - Centralized Operation Pipeline (
OperationRegistry,OperationBus): Auto-discovers services taggedphrame.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:
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:
- Resolve Operation: Look up
OperationInterfaceand itsOperationMetadatafromOperationRegistry(throwsOperationNotFoundExceptionif unknown). - 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 failedAuditRecord(stage: authorization) and throwAuthorizationException. - Dry-Run Capability Check: Rejects requests where
ExecutionContext::$dryRun === trueif!$metadata->supportsDryRunwith aValidationException. - Input Validation (
SchemaValidatorInterface::validate()): Validates$request->inputagainst$metadata->inputSchema(JSON Schema). ThrowsValidationExceptionon mismatch. - Idempotency Lookup (
IdempotencyStoreInterface::get()): For live executions (!$context->dryRun) carrying anidempotencyKey, checks for a cachedOperationResultkeyed by(actorId, operation, idempotencyKey). On cache hit, logs anAuditRecordwithreplayed: trueand returns the cached result without re-running the handler. - 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 failedAuditRecord(stage: execution) and rethrow. - Store Idempotent Result (
IdempotencyStoreInterface::put()): Persists theOperationResultfor live executions with anidempotencyKey. - Emit Audit Record (
AuditLoggerInterface::record()): Writes an immutableAuditRecordcapturingactorId,actorType,onBehalfOf,sessionId,operation,target,dryRun,success,beforeHash,afterHash,correlationId, and metadata.
Security default in
Kernel:Kernel::boot()only binds the dev-onlyAllowAllPolicyEnforcerwhenphramecms/useris not installed (!InstalledVersions::isInstalled('phramecms/user')). Wheneverphramecms/useris installed,UserModulebinds the deny-by-defaultRbacPolicyEnforcerasPolicyEnforcerInterfaceandDatabaseAuditLoggerasAuditLoggerInterface.
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 (TaggedContainerInterfaceextendsPsr\Container\ContainerInterface) - PSR-14 (
psr/event-dispatcher) — Domain event dispatching (EventDispatcherInterface,ListenerProviderInterface) - PSR-20 (
psr/clock) — Deterministic time viaPsr\Clock\ClockInterface(SystemClockdefault) - PSR-3 (
psr/log) — Logging contract inphramecms/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 inrouting,user,api,mcp, andadmin
- PSR-11 (
- Isolated vendor adapters:
- Twig (
twig/twig) is isolated strictly insidephramecms/admin, hidden behindPhrameCms\Admin\Contract\TemplateRendererInterface(TwigTemplateRenderer). No other module depends on Twig or renders HTML. - Doctrine DBAL is wrapped strictly inside
phramecms/database(DbalConnection,DbalQueryBuilder,DbalSchemaBuilder) behindConnectionInterface,QueryBuilderInterface, andSchemaBuilderInterface— allowing tests and lightweight tooling to swap inInMemoryConnectionwithout touching domain code.
- Twig (
- Transport parity: Because all business logic lives in
OperationInterfaceimplementations, 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 — Install and run the skeleton locally.
- Configuration Sync — Export, diff, import, and roll back Git-tracked configuration.
- Users, RBAC, and AI Agent Tokens — How
RbacPolicyEnforcer, tokens, and audit records work. - AI Change Proposals & Human Approval Queue — How
ProposalModulelayers human approval ontoOperationBus.