Custom Modules
Custom Modules Guide
Author, secure, package, and test custom PHP modules in PhrameCMS across the DI container, event bus, HTTP router, Admin UI, database schemas, and MCP.
Custom Modules Guide
This guide is the authoritative specification for authoring, securing, packaging, and testing custom modules in PhrameCMS. Every interface, constant, method signature, and invariant below reflects the merged contracts across phramecms/core, all 10 official modules (database, config, routing, user, entity, proposal, api, mcp, cli, admin), and phramecms/skeleton.
For quick lookup tables of all container tags, built-in operations, CLI commands, and runtime environment variables, see:
- Service Tags Reference
- Operations & MCP Reference
- CLI Commands Reference
- Environment Variables Reference
1. When to Use Config-Driven Entities vs. Custom PHP Modules
PhrameCMS separates declarative content modeling from custom PHP behavior. Prefer config-driven modeling whenever possible, and author a custom PHP module only when you need custom runtime logic or extension points.
Use Config-Driven Entities (Zero PHP Code) When:
- Defining or evolving content structures via
OperationBusoperations (./bin/phrame op:run, MCPtools/call, or/admin/schema):entity_type.create— create or update an entity type (for example,contentorcatalog)bundle.create— create or update a bundle with default workflow state andlabel_templatefield_storage.create— define reusable field storage using built-in types (string,text,integer,float,boolean,datetime,json,slug,entity_reference)field_instance.attach— attach fields with labels, descriptions,required,default_value,constraints, andapi_visible
- Managing editorial workflows (
draft→in_review→published→archived), RBAC roles/users, scoped AI agent tokens, Admin appearance (admin.settings), or Git-tracked configuration sync (config/sync/). - Every config-driven entity automatically gains JSON:API endpoints (
/api/v1/content/{entity_type}/{bundle}), OpenAPI 3.1 schema definitions, MCP tools and resources, CLI access, and/admin/contentCRUD forms with zero PHP code.
Author a Custom PHP Module (ModuleInterface) When:
- Exposing custom domain Operations through
OperationBus(automatically surfaced across CLI, MCP, and Change Proposals). - Subscribing to domain events (
EntityPreSaveEvent,EntityPostSaveEvent,ConfigChangedEvent, and others) or mutating schemas/specs via Alter events (BundleSchemaAlterEvent,OpenApiAlterEvent). - Managing custom relational database tables (
SchemaInstallerInterface). - Introducing new structured Field Types (
FieldTypeInterface) and/or custom Admin UI widgets (FieldFormWidgetInterface). - Adding custom HTTP endpoints, PSR-15 middleware, Admin pages / navigation / themes / Twig namespaces, CLI commands, config schemas, or read-only MCP resources.
2. Module Lifecycle & DI Container
ModuleInterface Contract
Every official and custom module implements PhrameCms\Core\Contract\ModuleInterface:
<?php
declare(strict_types=1);
namespace PhrameCms\Core\Contract;
use Psr\Container\ContainerInterface;
interface ModuleInterface
{
public function name(): string;
/** @return list<string> */
public function dependencies(): array;
public function register(ContainerBuilderInterface $builder): void;
public function boot(ContainerInterface $container): void;
}Topological Resolution & Two-Phase Boot
When new PhrameCms\Core\Kernel($modules) is constructed, PhrameCms\Core\Module\ModuleResolver::resolve() orders all modules using Kahn's algorithm with a SplMinHeap keyed by registration index:
- Dependencies always execute before dependents.
- Among modules whose dependencies are satisfied simultaneously, original declaration order is preserved deterministically.
- Empty or duplicate module names throw
PhrameCms\Core\Exception\CoreException. - Unregistered dependencies throw
PhrameCms\Core\Exception\MissingDependencyException. - Cycles throw
PhrameCms\Core\Exception\CircularDependencyExceptioncontaining the exact cycle path.
Kernel::boot() then executes an idempotent two-phase lifecycle (re-entrant boot() calls throw CoreException; calling boot() again after completion is a safe no-op):
- Register phase: Core registers built-in services (
Kernel,ClockInterface,ListenerProviderInterface,EventDispatcherInterface,SchemaValidatorInterface,IdempotencyStoreInterface,AuditLoggerInterface,OperationRegistry,OperationBus, plus a dev-onlyAllowAllPolicyEnforceronly whenphramecms/useris not installed). Then$module->register($builder)runs for each module in topological order. - Build & Boot phase:
$builder->build()produces an immutablePhrameCms\Core\Container\Container(implementingPhrameCms\Core\Contract\TaggedContainerInterface), and$module->boot($container)runs for each module in topological order.
Official module names for dependencies():
| Module Class | Dependency Constant / Value |
|---|---|
PhrameCms\Database\DatabaseModule |
DatabaseModule::NAME ('phrame.database') |
PhrameCms\Config\ConfigModule |
ConfigModule::NAME ('phrame.config') |
PhrameCms\Routing\RoutingModule |
RoutingModule::NAME ('phrame.routing') |
PhrameCms\User\UserModule |
UserModule::NAME ('phrame.user') |
PhrameCms\Entity\EntityModule |
EntityModule::NAME ('phrame.entity') |
PhrameCms\Proposal\ProposalModule |
ProposalModule::NAME ('phrame.proposal') |
PhrameCms\Api\ApiModule |
ApiModule::NAME ('phrame.api') |
PhrameCms\Mcp\McpModule |
McpModule::NAME ('phrame.mcp') |
PhrameCms\Cli\CliModule |
'phrame.cli' |
PhrameCms\Admin\AdminModule |
AdminModule::NAME ('phrame.admin') |
App\AppModule (skeleton) |
AppModule::NAME ('phrame.app') |
DI Container Ergonomics: autowire(), getTyped(), taggedAs()
PhrameCms\Core\Contract\ContainerBuilderInterface provides five registration primitives:
singleton(string $id, callable|string $factory, array $tags = []): void— shared service (closure receivesContainer, or zero-arg class-string).factory(string $id, callable|string $factory, array $tags = []): void— new instance perget().alias(string $alias, string $target): void— maps an interface or alias ID to a target service ID.tag(string $id, string $tag, int $priority = 0): void— attaches a tag with explicit priority (higher priority resolves first; ties preserve registration order).autowire(string $class, array $tags = [], bool $shared = true): void— registers a concreteclass-stringunder its own FQCN and resolves constructor parameters via reflection:- Named non-builtin class/interface type present in the container (
$container->has($paramType)) → resolved from the container. - Otherwise, if the parameter has a default value → uses the default value.
- Otherwise, if the parameter is typed and nullable → passes
null. - Otherwise → throws
PhrameCms\Core\Exception\ContainerException.
- Named non-builtin class/interface type present in the container (
PhrameCms\Core\Contract\TaggedContainerInterface (extends Psr\Container\ContainerInterface) provides type-safe resolution helpers:
tagged(string $tag): iterable— returns tagged services in descending priority order.getTyped(string $id, string $type): object— resolves$id, asserts$service instanceof $type(throwingContainerExceptionon mismatch), and narrows the static return type toT.taggedAs(string $tag, string $type): array— returnslist<T>in descending priority order, asserting every service implements$type.
<?php
declare(strict_types=1);
namespace Acme\Catalog;
use PhrameCms\Core\Contract\ContainerBuilderInterface;
use PhrameCms\Core\Contract\ModuleInterface;
use PhrameCms\Core\Contract\TaggedContainerInterface;
use PhrameCms\Core\Operation\OperationRegistry;
use PhrameCms\Database\Contract\SchemaInstallerInterface;
use PhrameCms\Database\DatabaseModule;
use Psr\Container\ContainerInterface;
final readonly class CatalogModule implements ModuleInterface
{
public const string NAME = 'acme.catalog';
public function name(): string
{
return self::NAME;
}
/** @return list<string> */
public function dependencies(): array
{
return [DatabaseModule::NAME];
}
public function register(ContainerBuilderInterface $builder): void
{
$builder->autowire(CatalogRepository::class);
$builder->autowire(CatalogSchemaInstaller::class, [SchemaInstallerInterface::SERVICE_TAG]);
$builder->autowire(CatalogSyncOperation::class, [OperationRegistry::OPERATION_TAG]);
}
public function boot(ContainerInterface $container): void
{
if ($container instanceof TaggedContainerInterface) {
$repo = $container->getTyped(CatalogRepository::class, CatalogRepository::class);
$installers = $container->taggedAs(
SchemaInstallerInterface::SERVICE_TAG,
SchemaInstallerInterface::class,
);
}
}
}Extension Points Overview
Custom modules plug into PhrameCMS exclusively via the 13 official DI container service tags (for example, phrame.operation, phrame.event_subscriber, phrame.schema_installer, phrame.field_type, phrame.route_provider, phrame.http_middleware, phrame.config_schema, phrame.cli_command, phrame.mcp_resource_provider, and the four phrame.admin_* tags). See the Service Tags Reference for every tag string, constant FQCN, interface, priority rule, and copy-paste registration snippet.
3. Event & Alter Bus
Subscription & Dispatch Mechanics
- Subscribers implement
PhrameCms\Core\Contract\EventSubscriberInterfaceand are tagged withEventSubscriberInterface::SERVICE_TAG('phrame.event_subscriber'). subscriptions()returnslist<EventSubscription>, wherenew EventSubscription(string $eventClass, string $method, int $priority = 0)binds a public callable method on the subscriber.PhrameCms\Core\Event\EventDispatcher(aliased asPsr\EventDispatcher\EventDispatcherInterface) invokes matching listeners in descending priority order (FIFO on ties), including listeners registered for parent classes or implemented interfaces.- Mutable alter hooks extend
PhrameCms\Core\Event\AlterEvent(which implementsPsr\EventDispatcher\StoppableEventInterface). Any listener can call$event->stopPropagation()to finalize the mutated structure and prevent lower-priority listeners from running.
<?php
declare(strict_types=1);
namespace Acme\Catalog\Event;
use PhrameCms\Core\Contract\EventSubscriberInterface;
use PhrameCms\Core\Event\EventSubscription;
use PhrameCms\Entity\Event\EntityPreSaveEvent;
final readonly class CatalogSubscriber implements EventSubscriberInterface
{
/** @return list<EventSubscription> */
public function subscriptions(): array
{
return [
new EventSubscription(EntityPreSaveEvent::class, 'onPreSave', priority: 10),
];
}
public function onPreSave(EntityPreSaveEvent $event): void
{
if ($event->entityType === 'catalog' && !isset($event->fields['summary'])) {
$event->setField('summary', 'Auto-generated summary');
}
}
}Built-In Events
| Event FQCN | Kind | Key Public Properties / Methods |
|---|---|---|
PhrameCms\Config\Event\ConfigChangedEvent |
Domain event (readonly) |
$operation, $diff (ConfigDiff), $actorId, $snapshotId, $occurredAt |
PhrameCms\Entity\Event\BundleSchemaAlterEvent |
AlterEvent (mutable) |
readonly $bundle (BundleDefinition), mutable $schema (array<string, mixed>) |
PhrameCms\Api\Event\OpenApiAlterEvent |
AlterEvent (mutable) |
mutable $spec (array<string, mixed>) |
PhrameCms\Entity\Event\EntityPreSaveEvent |
AlterEvent (mutable) |
mutable $fields + fields(), setField(), removeField(), setFields(); readonly $isNew, $entityId, $entityType, $bundle, $state, $actorId, $actorType, $previousRecord |
PhrameCms\Entity\Event\EntityPostSaveEvent |
Domain event (readonly) |
$record (EntityRecord), $isNew, $previousRecord, $actorId, $actorType |
PhrameCms\Entity\Event\EntityPreDeleteEvent |
Domain event (readonly) |
$record (EntityRecord) |
PhrameCms\Entity\Event\EntityPostDeleteEvent |
Domain event (readonly) |
$record (EntityRecord) |
PhrameCms\Entity\Event\EntityTransitionedEvent |
Domain event (readonly) |
$record (EntityRecord), $fromState (WorkflowState), $toState (WorkflowState), $actorId, $actorType |
Transaction & Dry-Run Invariants
- Pre-save runs before validation and before the DB transaction:
DatabaseEntityRepository::create()andupdate()dispatchEntityPreSaveEventafter defaults/merges and beforevalidateAndNormalizeFields()andrunInTransaction(). Fields added or altered by listeners are validated against the compiled bundle JSON Schema and persisted atomically. Throwing an exception aborts before any database write. - Post-save, post-delete, and transition run strictly post-commit:
EntityPostSaveEvent,EntityPostDeleteEvent, andEntityTransitionedEventfire only after the database transaction commits. Downstream side effects (webhooks, search indexing, custom audit rows) never observe uncommitted or rolled-back writes. - Pre-delete runs before the delete transaction:
EntityPreDeleteEventfires beforerunInTransaction(), allowing listeners to veto deletion by throwing an exception. - Zero mutation events on
dry_run: true:EntityCreateOperationandEntityUpdateOperationrun dry-run previews throughEntityFieldPreviewerwithout callingDatabaseEntityRepository— none of the 5Entity*Eventlifecycle events fire duringdry_run: true.ConfigManager::set(),delete(),import(), androllback()return early ondryRun: true(or empty diffs) without dispatchingConfigChangedEvent.- Read-time alter events (
BundleSchemaAlterEventandOpenApiAlterEvent) run whenever schemas or OpenAPI specs are compiled, including during dry-run validation.
4. HTTP Routing & Security Conventions
Register custom HTTP routes by implementing PhrameCms\Routing\Contract\RouteProviderInterface (tagged with RouteProviderInterface::SERVICE_TAG) and adding PhrameCms\Routing\Route definitions to RouteCollection.
PhrameCms\User\Http\BearerAuthMiddleware is registered globally on HttpKernel (priority 100) and enforces deny-by-default authentication for every route:
- Default — Bearer Token API Route (no
metaentry needed):- Requires
Authorization: Bearer <token>validated byPhrameCms\User\Contract\TokenAuthenticatorInterface. - Injects the authenticated
ActorInterfaceinto request attributeBearerAuthMiddleware::ACTOR_ATTRIBUTE('phrame.actor'). - Returns
401 Unauthorized(application/problem+json,WWW-Authenticate: Bearer) when the header is missing, duplicated, malformed, expired, or revoked. - Delegate domain reads and writes to
OperationBusso RBAC, JSON Schema validation, idempotency, and audit logging apply uniformly.
- Requires
- Public Route (
meta: ['public' => true]):- Permits unauthenticated requests only when no
Authorizationheader is present. If anAuthorizationheader is supplied,BearerAuthMiddlewarestill authenticates it and rejects invalid tokens with401. - Reserve strictly for intentionally public endpoints (such as
/api/v1/openapi.json,/admin/login, public site routes, or webhooks performing their own cryptographic verification).
- Permits unauthenticated requests only when no
- Admin Session Route (
meta: ['auth' => 'session']+middlewares: [AdminModule::SESSION_AUTH_MIDDLEWARE_SERVICE]):- Setting
meta: ['auth' => 'session']causesBearerAuthMiddlewareto hand off authentication to route-levelPhrameCms\User\Http\SessionAuthMiddleware(registered underAdminModule::SESSION_AUTH_MIDDLEWARE_SERVICE, value'phrame.admin.session_auth_middleware'). - Never set
meta: ['auth' => 'session']without also attachingAdminModule::SESSION_AUTH_MIDDLEWARE_SERVICEinmiddlewares:— doing so would leave the route unauthenticated. SessionAuthMiddlewarevalidates thephrame_sessioncookie (SessionCookie::DEFAULT_NAME), redirects unauthenticated visitors302 → /admin/login, setsBearerAuthMiddleware::ACTOR_ATTRIBUTE('phrame.actor') andSessionAuthMiddleware::SESSION_ATTRIBUTE('phrame.session'), and enforces CSRF token verification (_csrfparsed body field orX-CSRF-Tokenheader;403on failure) on everyPOST,PUT,PATCH, andDELETErequest.- Inside custom Admin controllers, enforce feature permissions via
OperationBusorPolicyEnforcerInterface::assertAllowed()to match anyrequiredPermissiondeclared onAdminMenuItem. - All
/adminresponses automatically receive strict security headers (Content-Security-Policy,X-Frame-Options: DENY,X-Content-Type-Options: nosniff,Referrer-Policy,Cache-Control) fromPhrameCms\Admin\Http\AdminSecurityHeadersMiddleware(registered at priority200).
- Setting
<?php
declare(strict_types=1);
namespace Acme\Catalog\Routing;
use Acme\Catalog\Http\CatalogController;
use PhrameCms\Admin\AdminModule;
use PhrameCms\Routing\Contract\RouteProviderInterface;
use PhrameCms\Routing\Route;
use PhrameCms\Routing\RouteCollection;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
final readonly class CatalogRouteProvider implements RouteProviderInterface
{
public function __construct(private CatalogController $controller) {}
public function registerRoutes(RouteCollection $routes): void
{
// Public health route
$routes->add(new Route(
name: 'acme.health',
methods: ['GET'],
path: '/acme/health',
handler: fn(ServerRequestInterface $r): ResponseInterface => $this->controller->health($r),
meta: ['public' => true],
));
// Bearer-authenticated API route (deny-by-default)
$routes->add(new Route(
name: 'acme.api.items',
methods: ['GET'],
path: '/api/v1/acme/items',
handler: fn(ServerRequestInterface $r): ResponseInterface => $this->controller->listItems($r),
));
// Session-authenticated Admin UI route (CSRF-protected for mutations)
$routes->add(new Route(
name: 'acme.admin.index',
methods: ['GET'],
path: '/admin/acme',
handler: fn(ServerRequestInterface $r): ResponseInterface => $this->controller->adminPage($r),
middlewares: [AdminModule::SESSION_AUTH_MIDDLEWARE_SERVICE],
meta: ['auth' => 'session'],
));
}
}5. Admin UI Extensibility
Sidebar Navigation (AdminMenuProviderInterface)
- Implement
PhrameCms\Admin\Contract\AdminMenuProviderInterface(tagphrame.admin_menu) and returnlist<AdminMenuItem>. AdminMenuBuildercollects all tagged menu providers, groups items by$item->group, sorts by$item->weight, and automatically hides any item whose$item->requiredPermissionis denied for the active actor viaPolicyEnforcerInterface.
Template Namespaces & Override Precedence (AdminTemplateNamespaceProviderInterface)
- Implement
PhrameCms\Admin\Contract\AdminTemplateNamespaceProviderInterface(tagphrame.admin_template_namespace) returningarray<string, string>mapping namespace names (matching/\A[a-z][a-z0-9_]*\z/, excluding reservedadmin_base) to template directories. TwigTemplateRendererregisters built-in Admin templates under@admin_baseand resolves default templates in precedence order:- Project overrides (
templates/admin/, orPHRAME_ADMIN_TEMPLATES_DIR) - Active theme paths (
AdminThemeInterface::templatePaths()) - Built-in
phramecms/admintemplates (@admin_base)
- Project overrides (
- For every custom module namespace (for example,
@acme),TwigTemplateRendererautomatically checks<projectOverridePath>/modules/<namespace>/(for example,templates/admin/modules/acme/) ahead of the module's own template directory. Site owners can override any individual module template without touchingvendor/. - Custom Admin pages should extend
layout.html.twig(to inherit the active theme) and render viaAdminResponder::renderPage($request, '@acme/page.html.twig', 'Page Title', $context), which automatically populatespage_title,current_path,csrf_token,actor,nav_groups, andtheme.
Custom Themes (AdminThemeInterface)
- Implement
PhrameCms\Admin\Contract\AdminThemeInterface(tagphrame.admin_theme) to expose a selectable Admin UI theme at/admin/appearanceor viaconfig/sync/admin.settings.json.
Custom Form Widgets (FieldFormWidgetInterface)
- Implement
PhrameCms\Admin\Contract\FieldFormWidgetInterface(tagphrame.admin_field_widget) to customize/admin/content/...HTML form rendering, value formatting, and POST submission coercion for any built-in or custom field type. SchemaFormMapperandFormViewBuilderresolvephrame.admin_field_widgetservices in descending tag priority order; the first widget wheresupports($fieldType)returnstruehandles that field type.inputType()must return one ofFormFieldDescriptor::INPUT_TYPES(text,textarea,number,checkbox,datetime-local,json,color,date,time,email,url,tel,range,search).- Returning a template name from
template()(for example,@acme/widgets/money.html.twig) causespartials/form_fields.html.twigto render{% include field.widget_template with { field: field } only %}; returningnullrenders the built-in HTML control. coerce()returnsFieldCoercionResult::value($v),FieldCoercionResult::empty(), orFieldCoercionResult::errors([new ValidationError(...)])(which surfaces inline per-field errors with HTTP422).
Hexagonal Twig Boundaries
- Twig (
Twig\Environment,Twig\Loader\FilesystemLoader) is strictly encapsulated insidePhrameCms\Admin\Bridge\TwigTemplateRenderer(Anti-Corruption Layer) and is never exposed in any public PhrameCMS contract or method signature. TwigTemplateRendererenforcesautoescape => 'html'andstrict_variables => true. Custom modules MUST depend only onPhrameCms\Admin\Contract\TemplateRendererInterfaceorPhrameCms\Admin\Http\AdminResponderand pass plain associative arrays into.html.twigtemplates.
6. Database Schemas & Packaging
Portable, Idempotent Schemas (SchemaInstallerInterface)
- Implement
PhrameCms\Database\Contract\SchemaInstallerInterface(tagphrame.schema_installer). - Define tables through
ConnectionInterface::schema()->createTable($table, fn(TableBlueprint $t) => ...)usingPhrameCms\Database\Schema\ColumnType(String,Text,Integer,BigInt,Float,Boolean,DateTime,Json). - Always guard
install()withif ($this->isInstalled()) { return; }so./bin/phrame site:installand./bin/phrame schema:installremain strictly idempotent across SQLite, PostgreSQL, and MariaDB/MySQL.
Module Discovery & Reusable Composer Packaging
phramecms/skeleton ships App\ModuleDiscovery wired into App\AppBootstrap::boot(), so custom modules work uniformly across public/index.php, bin/phrame, and bin/phrame-mcp with zero entrypoint edits:
- Project-local modules (
config/modules.php):
<?php
declare(strict_types=1);
return [
App\Module\Catalog\CatalogModule::class,
new App\Module\Custom\CustomModule(apiKey: $_ENV['CUSTOM_KEY'] ?? ''),
];- Reusable Composer packages (
composer.json):
{
"name": "acme/phramecms-catalog",
"type": "library",
"require": {
"php": "^8.5",
"phramecms/core": "^0.1"
},
"autoload": {
"psr-4": { "Acme\\Catalog\\": "src/" }
},
"extra": {
"phramecms": {
"modules": [
"Acme\\Catalog\\CatalogModule"
]
}
}
}App\ModuleDiscoveryscansvendor/composer/installed.json(sorted deterministically by package name) unlessPHRAME_DISCOVER_COMPOSER_MODULES=0.- Auto-instantiated module classes declared as class-strings (in
config/modules.phporextra.phramecms.modules) must have zero required constructor arguments; modules requiring constructor arguments should be instantiated directly inconfig/modules.php. - Deduplication precedence when the same module class appears in multiple sources: built-in modules >
$extraModules>config/modules.php> Composerextra.phramecms.modules. - Two different classes declaring the same
ModuleInterface::name()fail fast with an actionableRuntimeException.
7. Testing Custom Modules
Custom modules MUST be tested completely in-process with zero external database servers, using PhrameCms\Database\Driver\InMemoryConnection (memory://) or a temporary SQLite file inside sys_get_temp_dir().
<?php
declare(strict_types=1);
namespace Acme\Catalog\Tests;
use Acme\Catalog\CatalogModule;
use Nyholm\Psr7\ServerRequest;
use PhrameCms\Core\Contract\TaggedContainerInterface;
use PhrameCms\Core\Kernel;
use PhrameCms\Core\Operation\ExecutionContext;
use PhrameCms\Core\Operation\OperationBus;
use PhrameCms\Core\Operation\OperationRequest;
use PhrameCms\Core\Security\ActorType;
use PhrameCms\Database\DatabaseModule;
use PhrameCms\Database\Schema\SchemaInstallRunner;
use PhrameCms\Mcp\Contract\McpServerInterface;
use PhrameCms\Mcp\McpModule;
use PhrameCms\Mcp\Protocol\JsonRpcRequest;
use PhrameCms\Routing\HttpKernel;
use PhrameCms\Routing\RoutingModule;
use PhrameCms\User\Security\AuthenticatedActor;
use PhrameCms\User\UserModule;
use PHPUnit\Framework\TestCase;
final class CatalogModuleTest extends TestCase
{
public function testCustomModuleEndToEndInMemory(): void
{
$kernel = new Kernel([
new DatabaseModule('memory://'),
new RoutingModule(),
new UserModule(),
new McpModule(),
new CatalogModule(),
]);
$kernel->boot();
$container = $kernel->container();
self::assertInstanceOf(TaggedContainerInterface::class, $container);
// 1. Install all registered schemas (official + custom)
$container->getTyped(SchemaInstallRunner::class, SchemaInstallRunner::class)->installAll();
// 2. Exercise OperationBus (dry-run + live) with a scoped Agent actor
$bus = $container->getTyped(OperationBus::class, OperationBus::class);
$actor = new AuthenticatedActor(
id: 'agt_test_runner',
type: ActorType::Agent,
scopes: ['acme.notes.write', 'acme.read'],
);
$result = $bus->execute(new OperationRequest(
operation: 'acme.note.create',
input: ['slug' => 'hello', 'body' => 'world'],
context: new ExecutionContext(actor: $actor, correlationId: 'test-1', dryRun: true),
));
self::assertTrue($result->dryRun);
// 3. Exercise HttpKernel (public or authenticated routes)
$http = $container->getTyped(HttpKernel::class, HttpKernel::class);
$response = $http->handle(new ServerRequest('GET', '/acme/health'));
self::assertSame(200, $response->getStatusCode());
// 4. Exercise McpServer (tools/call & resources/read)
$mcp = $container->getTyped(McpServerInterface::class, McpServerInterface::class);
$rpc = $mcp->handle(
new JsonRpcRequest(jsonrpc: '2.0', id: 1, method: 'resources/list', params: []),
$actor,
);
self::assertNotNull($rpc);
}
}Inside a phramecms/skeleton project, you can boot the complete 10-module stack (including config/modules.php discovery, AdminModule, EntityModule, ProposalModule, and CliApplication) directly via:
$kernel = App\AppBootstrap::boot(new App\AppConfig(
projectRoot: $tempDir,
dsn: 'memory://',
configSyncDir: $tempDir . '/config/sync',
debug: false,
discoverComposerModules: false,
));