Version 1.0 Baseline • Production Ready

The Contract-Driven PHP Framework

Built for high-scale APIs, modern web apps, and background workers. Combining Laravel's beloved ergonomics with strict layered architecture, OWASP ASVS Level 2 security, zero-leak DI, and native N+1 prevention.

$ php cna serve

How CnA Framework Works

Controllers handle transport concerns only. Use cases live in Application Services that coordinate business rules and own explicit database transaction boundaries.

1

HTTP Request

Normalized headers, query parameters, cookies, JSON bodies, and correlation ID extraction.

Request::createFromGlobals()
2

Kernel & Middleware

Global onion pipeline enforcing HSTS, CSP, X-Frame-Options, rate limiting, and CSRF protection.

Kernel->handle($request)
3

Router & Regex Verbs

Fast URI parameter parsing, regex constraints, named route lookups, and group prefixes.

$router->dispatch($request)
4

Thin Controller

Parses & validates input with Validator, then delegates directly to an Application Service.

OrderController->store()
5

Application Service

Coordinates domain rules and owns explicit database transaction boundaries using savepoints.

CreateOrderService->execute()
6

Domain & Repository

Pure entity domain logic and repository interfaces decoupled from persistence drivers.

OrderRepositoryInterface
7

ORM & Query Builder

Active Record / Data Mapper hybrid models with mass assignment safeguards and O(1) eager loading.

Order::with(['items'])->get()
8

Database Engine

Multi-dialect PDO connection manager (SQLite, MySQL, PostgreSQL) with N+1 query observability.

ConnectionManager::class

Built-In Engineering Features

Engineered from first principles with zero external runtime baggage and uncompromising security defaults.

🛡️

OWASP ASVS Level 2 Security

AES-256-GCM authenticated encryption (AEAD), Argon2id password hashing, automated SSRF defenses blocking private/loopback/metadata IP ranges, and constant-time secret comparisons.

AEAD Encryption SSRF Guard Argon2id
🔍

First-Class N+1 Prevention

Strict-mode lazy loading prevention throws actionable diagnostics when relations are accessed dynamically without eager loading. Normalized SQL fingerprinting and per-route query budgets.

Strict Mode Query Budgets SQL Fingerprints
💉

Zero-Leak DI Container

Reflection-based autowiring, interface bindings, transient/singleton/scoped lifetimes, tagged service resolution, and circular dependency graph detection.

Autowiring Circular Guard Tagged Services
🤖

Pluggable AI Subsystem

Vendor-independent AI contracts with PromptGuard prompt injection defenses, secret redactors, tenant token usage accounting, permissioned tool registries with audit logs, and in-memory RAG.

PromptGuard Token Quotas Vector Store
⚡

Async Queues & Scheduler

Transactional queue worker daemon with exponential backoff, retry ceilings, and failed-job logging. Task scheduler with mutex lock-based overlap prevention.

Worker Daemon Failed Jobs Cron Mutex
📦

Strict Modular Monorepo

27 decoupled packages under the `CnA\` namespace. The contracts package never depends on concrete adapters, ensuring true dependency inversion.

27 Packages Pure Contracts Clean Architecture

The `cna` Command Suite

Comprehensive CLI developer tools for serving, migrating, profiling, seeding, and scaffolding code.

Command Description Action
php cna serve Start the local development server (supports --host and --port)
php cna doctor Run comprehensive diagnostic checks on PHP 8.4+, PDO drivers, and environment
php cna security:check Audit configuration against OWASP ASVS baseline security verification rules
php cna route:list Display formatted table of all registered HTTP routes, actions, and middlewares
php cna db:status Show status (Ran vs Pending) and batch of each database migration
php cna migrate Execute all pending database migrations in transaction batches
php cna migrate:rollback Rollback the last migration batch
php cna migrate:refresh Rollback all database migrations and re-run them from scratch (supports --seed)
php cna db:seed Seed the database with seed records (e.g. DatabaseSeeder)
php cna db:profile Inspect query execution counts, total latency, and detect N+1 query patterns
php cna test Run the complete automated test suite (Unit, Feature, and Architecture tests)
php cna key:generate Generate and set the 256-bit AEAD application encryption key in .env
php cna queue:work Start processing background jobs from the queue with automatic retry backoff
php cna queue:failed List failed queue jobs with exception details and stack traces
php cna schedule:run Execute due scheduled cron events with distributed lock overlap prevention
php cna ai:usage Report AI token consumption, tenant quotas, and budget metrics
php cna make:controller <Name> Scaffold a thin transport controller class in app/Http/Controllers/
php cna make:service <Name> Scaffold an application service use case with transaction management
php cna make:repository <Name> Scaffold domain repository interface & SQL infrastructure implementation
php cna make:model <Name> Scaffold an ORM Model class with mass-assignment protection
php cna make:migration <name> Create a new schema blueprint migration file

Helper Functions & API Cheat Sheet

Familiar, expressive functions that resolve from the DI container without exposing global mutable state.

app(?string $abstract = null)
Resolve services from the dependency injection container.
$db = app(\CnA\Contracts\Database\ConnectionInterface::class);
config(?string $key = null, mixed $default = null)
Get dot-notated typed configuration parameters.
$driver = config('database.default', 'sqlite');
env(string $key, mixed $default = null)
Read environment variables with automatic type conversion.
$debug = env('APP_DEBUG', false);
json(mixed $data = [], int $status = 200)
Return a JSON response with security headers.
return json(['success' => true, 'data' => $order]);
view(string $view, array $data = [])
Render an HTML template with auto-escaping.
return view('welcome', ['title' => 'Dashboard']);
route(string $name, array $params = [])
Generate a URL to a named route.
$url = route('orders.show', ['id' => 42]);
abort(int $code, string $message = '')
Throw documented framework HTTP exceptions.
abort(404, 'Order was not found.');
bcrypt(string $value, array $options = [])
Securely hash passwords using native algorithms.
$hash = bcrypt('my-secret-password');

Live API Playground

Test your running framework endpoints directly from this page using live fetch requests.

// Click "Send Request" to test endpoint live...