---
title: 'Custom Modules Guide'
url: 'http://phramecms.org/docs/custom-modules'
markdown_url: 'http://phramecms.org/docs/custom-modules.md'
bundle: guide
section: custom-modules
summary: 'Author, secure, package, and test custom PHP modules in PhrameCMS across the DI container, event bus, HTTP router, Admin UI, database schemas, and MCP.'
source: 'https://github.com/PhrameCMS/docs/blob/main/guides/custom-modules.md'
updated_at: '2026-12-04T22:12:22+00:00'
---

# 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](../reference/service-tags.md)
- [Operations & MCP Reference](../reference/operations-mcp.md)
- [CLI Commands Reference](../reference/cli-commands.md)
- [Environment Variables Reference](../reference/env-vars.md)

---

## 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 `OperationBus` operations (`./bin/phrame op:run`, MCP `tools/call`, or `/admin/schema`):
  - `entity_type.create` — create or update an entity type (for example, `content` or `catalog`)
  - `bundle.create` — create or update a bundle with default workflow state and `label_template`
  - `field_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`, and `api_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/content` CRUD 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
<?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\CircularDependencyException` containing 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):

1. **Register phase**: Core registers built-in services (`Kernel`, `ClockInterface`, `ListenerProviderInterface`, `EventDispatcherInterface`, `SchemaValidatorInterface`, `IdempotencyStoreInterface`, `AuditLoggerInterface`, `OperationRegistry`, `OperationBus`, plus a dev-only `AllowAllPolicyEnforcer` only when `phramecms/user` is not installed). Then `$module->register($builder)` runs for each module in topological order.
2. **Build & Boot phase**: `$builder->build()` produces an immutable `PhrameCms\Core\Container\Container` (implementing `PhrameCms\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 receives `Container`, or zero-arg class-string).
- `factory(string $id, callable|string $factory, array $tags = []): void` — new instance per `get()`.
- `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 concrete `class-string` under its own FQCN and resolves constructor parameters via reflection:
  1. Named non-builtin class/interface type present in the container (`$container->has($paramType)`) → resolved from the container.
  2. Otherwise, if the parameter has a default value → uses the default value.
  3. Otherwise, if the parameter is typed and nullable → passes `null`.
  4. Otherwise → throws `PhrameCms\Core\Exception\ContainerException`.

`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` (throwing `ContainerException` on mismatch), and narrows the static return type to `T`.
- `taggedAs(string $tag, string $type): array` — returns `list<T>` in descending priority order, asserting every service implements `$type`.

```php
<?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](../reference/service-tags.md) 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\EventSubscriberInterface` and are tagged with `EventSubscriberInterface::SERVICE_TAG` (`'phrame.event_subscriber'`).
- `subscriptions()` returns `list<EventSubscription>`, where `new EventSubscription(string $eventClass, string $method, int $priority = 0)` binds a public callable method on the subscriber.
- `PhrameCms\Core\Event\EventDispatcher` (aliased as `Psr\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 implements `Psr\EventDispatcher\StoppableEventInterface`). Any listener can call `$event->stopPropagation()` to finalize the mutated structure and prevent lower-priority listeners from running.

```php
<?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

1. **Pre-save runs before validation and before the DB transaction**: `DatabaseEntityRepository::create()` and `update()` dispatch `EntityPreSaveEvent` after defaults/merges and **before** `validateAndNormalizeFields()` and `runInTransaction()`. 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.
2. **Post-save, post-delete, and transition run strictly post-commit**: `EntityPostSaveEvent`, `EntityPostDeleteEvent`, and `EntityTransitionedEvent` fire **only after** the database transaction commits. Downstream side effects (webhooks, search indexing, custom audit rows) never observe uncommitted or rolled-back writes.
3. **Pre-delete runs before the delete transaction**: `EntityPreDeleteEvent` fires before `runInTransaction()`, allowing listeners to veto deletion by throwing an exception.
4. **Zero mutation events on `dry_run: true`**:
   - `EntityCreateOperation` and `EntityUpdateOperation` run dry-run previews through `EntityFieldPreviewer` without calling `DatabaseEntityRepository` — **none** of the 5 `Entity*Event` lifecycle events fire during `dry_run: true`.
   - `ConfigManager::set()`, `delete()`, `import()`, and `rollback()` return early on `dryRun: true` (or empty diffs) without dispatching `ConfigChangedEvent`.
   - Read-time alter events (`BundleSchemaAlterEvent` and `OpenApiAlterEvent`) 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:

1. **Default — Bearer Token API Route** (no `meta` entry needed):
   - Requires `Authorization: Bearer <token>` validated by `PhrameCms\User\Contract\TokenAuthenticatorInterface`.
   - Injects the authenticated `ActorInterface` into request attribute `BearerAuthMiddleware::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 `OperationBus` so RBAC, JSON Schema validation, idempotency, and audit logging apply uniformly.
2. **Public Route** (`meta: ['public' => true]`):
   - Permits unauthenticated requests **only when no `Authorization` header is present**. If an `Authorization` header *is* supplied, `BearerAuthMiddleware` still authenticates it and rejects invalid tokens with `401`.
   - Reserve strictly for intentionally public endpoints (such as `/api/v1/openapi.json`, `/admin/login`, public site routes, or webhooks performing their own cryptographic verification).
3. **Admin Session Route** (`meta: ['auth' => 'session']` + `middlewares: [AdminModule::SESSION_AUTH_MIDDLEWARE_SERVICE]`):
   - Setting `meta: ['auth' => 'session']` causes `BearerAuthMiddleware` to hand off authentication to route-level `PhrameCms\User\Http\SessionAuthMiddleware` (registered under `AdminModule::SESSION_AUTH_MIDDLEWARE_SERVICE`, value `'phrame.admin.session_auth_middleware'`).
   - **Never** set `meta: ['auth' => 'session']` without also attaching `AdminModule::SESSION_AUTH_MIDDLEWARE_SERVICE` in `middlewares:` — doing so would leave the route unauthenticated.
   - `SessionAuthMiddleware` validates the `phrame_session` cookie (`SessionCookie::DEFAULT_NAME`), redirects unauthenticated visitors `302 → /admin/login`, sets `BearerAuthMiddleware::ACTOR_ATTRIBUTE` (`'phrame.actor'`) and `SessionAuthMiddleware::SESSION_ATTRIBUTE` (`'phrame.session'`), and enforces CSRF token verification (`_csrf` parsed body field or `X-CSRF-Token` header; `403` on failure) on every `POST`, `PUT`, `PATCH`, and `DELETE` request.
   - Inside custom Admin controllers, enforce feature permissions via `OperationBus` or `PolicyEnforcerInterface::assertAllowed()` to match any `requiredPermission` declared on `AdminMenuItem`.
   - All `/admin` responses automatically receive strict security headers (`Content-Security-Policy`, `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy`, `Cache-Control`) from `PhrameCms\Admin\Http\AdminSecurityHeadersMiddleware` (registered at priority `200`).

```php
<?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` (tag `phrame.admin_menu`) and return `list<AdminMenuItem>`.
- `AdminMenuBuilder` collects all tagged menu providers, groups items by `$item->group`, sorts by `$item->weight`, and automatically hides any item whose `$item->requiredPermission` is denied for the active actor via `PolicyEnforcerInterface`.

### Template Namespaces & Override Precedence (`AdminTemplateNamespaceProviderInterface`)

- Implement `PhrameCms\Admin\Contract\AdminTemplateNamespaceProviderInterface` (tag `phrame.admin_template_namespace`) returning `array<string, string>` mapping namespace names (matching `/\A[a-z][a-z0-9_]*\z/`, excluding reserved `admin_base`) to template directories.
- `TwigTemplateRenderer` registers built-in Admin templates under `@admin_base` and resolves default templates in precedence order:
  1. Project overrides (`templates/admin/`, or `PHRAME_ADMIN_TEMPLATES_DIR`)
  2. Active theme paths (`AdminThemeInterface::templatePaths()`)
  3. Built-in `phramecms/admin` templates (`@admin_base`)
- For every custom module namespace (for example, `@acme`), `TwigTemplateRenderer` automatically 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 touching `vendor/`.
- Custom Admin pages should extend `layout.html.twig` (to inherit the active theme) and render via `AdminResponder::renderPage($request, '@acme/page.html.twig', 'Page Title', $context)`, which automatically populates `page_title`, `current_path`, `csrf_token`, `actor`, `nav_groups`, and `theme`.

### Custom Themes (`AdminThemeInterface`)

- Implement `PhrameCms\Admin\Contract\AdminThemeInterface` (tag `phrame.admin_theme`) to expose a selectable Admin UI theme at `/admin/appearance` or via `config/sync/admin.settings.json`.

### Custom Form Widgets (`FieldFormWidgetInterface`)

- Implement `PhrameCms\Admin\Contract\FieldFormWidgetInterface` (tag `phrame.admin_field_widget`) to customize `/admin/content/...` HTML form rendering, value formatting, and POST submission coercion for any built-in or custom field type.
- `SchemaFormMapper` and `FormViewBuilder` resolve `phrame.admin_field_widget` services in descending tag priority order; the first widget where `supports($fieldType)` returns `true` handles that field type.
- `inputType()` must return one of `FormFieldDescriptor::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`) causes `partials/form_fields.html.twig` to render `{% include field.widget_template with { field: field } only %}`; returning `null` renders the built-in HTML control.
- `coerce()` returns `FieldCoercionResult::value($v)`, `FieldCoercionResult::empty()`, or `FieldCoercionResult::errors([new ValidationError(...)])` (which surfaces inline per-field errors with HTTP `422`).

### Hexagonal Twig Boundaries

- Twig (`Twig\Environment`, `Twig\Loader\FilesystemLoader`) is strictly encapsulated inside `PhrameCms\Admin\Bridge\TwigTemplateRenderer` (Anti-Corruption Layer) and is **never** exposed in any public PhrameCMS contract or method signature.
- `TwigTemplateRenderer` enforces `autoescape => 'html'` and `strict_variables => true`. Custom modules MUST depend only on `PhrameCms\Admin\Contract\TemplateRendererInterface` or `PhrameCms\Admin\Http\AdminResponder` and pass plain associative arrays into `.html.twig` templates.

---

## 6. Database Schemas & Packaging

### Portable, Idempotent Schemas (`SchemaInstallerInterface`)

- Implement `PhrameCms\Database\Contract\SchemaInstallerInterface` (tag `phrame.schema_installer`).
- Define tables through `ConnectionInterface::schema()->createTable($table, fn(TableBlueprint $t) => ...)` using `PhrameCms\Database\Schema\ColumnType` (`String`, `Text`, `Integer`, `BigInt`, `Float`, `Boolean`, `DateTime`, `Json`).
- Always guard `install()` with `if ($this->isInstalled()) { return; }` so `./bin/phrame site:install` and `./bin/phrame schema:install` remain 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:

1. **Project-local modules (`config/modules.php`)**:

```php
<?php

declare(strict_types=1);

return [
    App\Module\Catalog\CatalogModule::class,
    new App\Module\Custom\CustomModule(apiKey: $_ENV['CUSTOM_KEY'] ?? ''),
];
```

2. **Reusable Composer packages (`composer.json`)**:

```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\ModuleDiscovery` scans `vendor/composer/installed.json` (sorted deterministically by package name) unless `PHRAME_DISCOVER_COMPOSER_MODULES=0`.
- Auto-instantiated module classes declared as class-strings (in `config/modules.php` or `extra.phramecms.modules`) must have zero required constructor arguments; modules requiring constructor arguments should be instantiated directly in `config/modules.php`.
- Deduplication precedence when the same module class appears in multiple sources: **built-in modules > `$extraModules` > `config/modules.php` > Composer `extra.phramecms.modules`**.
- Two different classes declaring the same `ModuleInterface::name()` fail fast with an actionable `RuntimeException`.

---

## 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
<?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:

```php
$kernel = App\AppBootstrap::boot(new App\AppConfig(
    projectRoot: $tempDir,
    dsn: 'memory://',
    configSyncDir: $tempDir . '/config/sync',
    debug: false,
    discoverComposerModules: false,
));
```
