cna / framework
CnA Framework - Technical Architecture & Implementation
Requires
- php: >=8.4
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-07 23:25:46 UTC
README
The Contract-Driven PHP Framework
Secure โข Scalable โข Intelligent
๐ About CnA Framework
CnA Framework is a contract-driven, high-performance PHP 8.4+ modular monorepo framework built for mission-critical web applications, high-throughput APIs, and background worker systems. It pairs the beloved developer ergonomics of Laravel with strict architectural boundaries, native OWASP ASVS Level 2 defenses, zero-leak dependency injection, built-in $O(1)$ eager loading with N+1 query prevention, and a provider-independent AI subsystem.
๐จโ๐ป Framework Architect & Lead Developer
- Author: Alan Shaju (Senior Software Engineer)
- LinkedIn: https://www.linkedin.com/in/alanshaju2k2/
- GitHub: https://github.com/Alan2k2
โก Quick Start & Running the Welcome Interface
๐ Live Online Demo (No Installation Required)
You can directly assess the framework UI, features, commands, and interactive API sandbox online: ๐ https://alan2k2.github.io/CnA-Framework/
Local Installation & Running:
1. Clone & Setup
git clone https://github.com/Alan2k2/CnA-Framework.git
cd CnA-Framework
2. Environment Setup
cp .env.example .env php cna key:generate
3. Start the Development Server
php cna serve
(or on Windows: cna serve)
4. Access the Welcome Interface
Open your browser and navigate to: ๐ http://127.0.0.1:8000
Visiting this URL displays the CnA Framework Interactive Interface (welcome.php) featuring:
- Official glowing logo and responsive dark theme UI.
- Interactive Architecture & Request Lifecycle Explorer.
- Comprehensive breakdown of all 27 Decoupled Packages.
- Searchable CLI Command Reference.
- Interactive Core Helper Functions Guide.
- Live API Playground allowing you to test endpoints directly from the browser!
๐ Key Highlights & Architecture
CnA Framework is built strictly according to enterprise software engineering standards:
-
Strict Layered Architecture:
- Thin transport controllers parse/validate input, invoke application use cases, and serialize responses.
- Application use cases coordinate business rules and own explicit transaction boundaries via
TransactionManagerInterface. - Domain rules and repository interfaces are completely decoupled from HTTP transport and PDO infrastructure.
-
First-Class N+1 Prevention & Query Observability:
- Strict mode in development/testing throws
LazyLoadingViolationExceptionon unexpected dynamic lazy loading. - Fast $O(1)$ eager loading via
Model::with(['user', 'items'])->get(). - Built-in
QueryObserverwith normalized SQL fingerprinting, repeated relation query detection, and route/job query budgets.
- Strict mode in development/testing throws
-
OWASP ASVS Level 2 Baseline Security:
- AEAD authenticated encryption (AES-256-GCM) with tag verification and key rotation.
- Argon2id password hashing by default with Bcrypt fallback.
- Constant-time secret/token comparisons (
hash_equals). - Automated SSRF defenses blocking private/loopback/metadata IP ranges (127.0.0.0/8, 10.0.0.0/8, 192.168.0.0/16, 169.254.169.254, ::1).
- Strict SQL parameter binding and dialect identifier quoting (SQLite, MySQL, PostgreSQL).
- Secure HTTP response headers (HSTS, CSP, X-Frame-Options, X-Content-Type-Options).
-
Provider-Independent AI Subsystem:
- Pluggable provider abstraction (
AIProviderInterface,EmbeddingProviderInterface,TokenCounterInterface). - Built-in
FakeAIProviderfor deterministic, zero-external-dependency offline testing with recorded chat assertions. -
PromptGuard: Detects prompt injections and redacts sensitive tokens/secrets prior to external transmission. -
CostTracker: Enforces tenant token quotas, approved model allowlists, and usage metrics. -
ToolRegistry: Permissioned tool execution with execution schemas, timeouts, and structured audit trails. -
VectorStore: In-memory RAG vector store with cosine similarity and tenant isolation filtering.
- Pluggable provider abstraction (
-
Turnkey CLI Experience (
php cnaor./cna):- Generators:
make:controller,make:service,make:repository,make:model,make:migration - Migrations:
migrate,migrate:rollback,migrate:refresh,db:status - Diagnostics:
doctor,route:list,db:profile,security:check,about - AI Diagnostics:
ai:diagnose,ai:providers,ai:usage - Operations:
serve,cache:clear,queue:work,queue:retry,queue:flush,schedule:run,test,benchmark
- Generators:
๐ Repository & Monorepo Structure
cna-framework/
โโโ cna # CLI executable script
โโโ cna.bat # Windows native CLI launcher
โโโ server.php # Dev server rewrite router
โโโ composer.json # Monorepo composer configuration
โโโ .env.example # Environment template
โโโ packages/ # 27 Modular Packages (independent composer manifests)
โ โโโ contracts/ # Core interfaces (Container, DB, HTTP, AI, Cache, etc.)
โ โโโ core/ # Application engine, pipeline, service providers & helpers
โ โโโ container/ # DI container with autowiring, singletons, scoped & circular detection
โ โโโ config/ # Dot-notation typed configuration & Env parser
โ โโโ console/ # CLI console bus, styling, table renderer & commands
โ โโโ http/ # Normalized Request, Response, JsonResponse & Kernel
โ โโโ routing/ # Fluent Router, route groups, named routes, parameter constraints
โ โโโ middleware/ # Security headers, CSRF token guard, rate limiter, CORS
โ โโโ validation/ # Input validator & typed FormRequest
โ โโโ database/ # Multi-driver PDO connection manager & transaction manager
โ โโโ query-builder/ # Fluent Query Builder with SQLite/MySQL/PostgreSQL dialects
โ โโโ orm/ # Active Record / Data Mapper hybrid models & relationships
โ โโโ migrations/ # Schema builder, blueprints, migration runner & rollbacks
โ โโโ auth/ # Authentication manager, guards & password hashing
โ โโโ authorization/ # Gate & RBAC policy system (deny-by-default)
โ โโโ security/ # AEAD Encrypter, CSRF manager, SSRF validator, HTML escaper
โ โโโ cache/ # Cache manager (array, file, database stores & atomic locks)
โ โโโ queue/ # Queue manager, sync & database drivers, worker daemon
โ โโโ events/ # Event dispatcher & subscribers
โ โโโ scheduler/ # Cron task scheduler with overlap prevention
โ โโโ mail/ # Mailer abstraction, Mailables & test fakes
โ โโโ notifications/ # Multi-channel notification subsystem
โ โโโ storage/ # Filesystem abstraction with traversal defense
โ โโโ ai/ # AI Chat, Streaming, Embeddings, RAG, Tools & Safety
โ โโโ logging/ # Structured logger with secret redactor & correlation IDs
โ โโโ monitoring/ # QueryObserver, query budgets & N+1 detection engine
โ โโโ testing/ # TestCase, TestResponse, TestRunner & assertions
โโโ skeleton/ # Reference application starter (like laravel/laravel)
โ โโโ app/
โ โ โโโ Http/Controllers/ # Thin transport controllers
โ โ โโโ Application/ # Use cases & Commands (e.g. CreateOrderService)
โ โ โโโ Domain/ # Entities & Repository Interfaces (Order, User)
โ โ โโโ Infrastructure/ # SQL Repository implementations
โ โ โโโ Models/ # ORM Models (User, Order, OrderItem)
โ โโโ bootstrap/app.php # Application bootstrapping & provider registration
โ โโโ config/ # Environment-specific configuration files
โ โโโ database/migrations/ # Versioned database migrations
โ โโโ public/index.php # HTTP web entrypoint
โ โโโ routes/ # api.php and web.php route definitions
โโโ benchmarks/ # Micro-benchmarks & baseline metrics
โโโ docs/adr/ # Architecture Decision Records (ADRs 0001 - 0008)
โโโ tests/ # Unit, Feature, and Architecture test suite
๐ ๏ธ Unified CLI Reference
Run commands using php cna <command>:
| Command | Category | Description |
|---|---|---|
serve |
General | Start the local development web server with URL rewriting |
doctor |
General | Verify runtime health, extensions, storage writability, and .env |
security:check |
Security | Audit configuration against OWASP ASVS baseline security rules |
test |
General | Run the automated test suite (34 passing tests) |
benchmark |
General | Run framework micro-benchmarks for DI, routing, and ORM |
route:list |
Routing | Display all registered HTTP routes, methods, names, and actions |
db:status |
Database | Show status and batch of each database migration |
migrate |
Database | Execute pending database migrations |
migrate:rollback |
Database | Rollback the last migration batch |
migrate:refresh |
Database | Rollback all migrations and run them again |
db:profile |
Database | Display query logs and detect potential N+1 query patterns |
db:seed |
Database | Seed the database with records |
cache:clear |
Cache | Flush the application cache |
queue:work |
Queue | Start the background queue worker daemon |
queue:failed |
Queue | List failed queue jobs |
queue:retry |
Queue | Retry a failed job by ID or retry all |
queue:flush |
Queue | Flush all failed queue jobs |
schedule:run |
Scheduler | Run scheduled cron tasks |
ai:usage |
AI | Report token consumption and tenant quota usage |
ai:providers |
AI | List configured AI providers and model allowlist |
ai:diagnose |
AI | Run diagnostic connectivity & PromptGuard injection checks |
key:generate |
Security | Generate and set the 256-bit AEAD application encryption key |
make:controller |
Generator | Scaffold a thin transport controller |
make:service |
Generator | Scaffold an application use case service |
make:repository |
Generator | Scaffold a domain repository interface and SQL implementation |
make:model |
Generator | Scaffold an ORM model class |
make:migration |
Generator | Create a new versioned database migration |
๐งช Testing & Micro-Benchmarks
Run the test suite:
php cna test
All 34 automated tests pass with zero external dependencies.
Run micro-benchmarks:
php cna benchmark
- Container Resolution: ~400,000 ops/second (~2.5 ยตs/op)
- Router Match: ~40,000 ops/second (~25 ยตs/op)
- QueryBuilder Compilation: ~47,000 ops/second (~21 ยตs/op)
- Model Hydration: ~650,000 ops/second (~1.5 ยตs/op)
๐ License
The CnA Framework is open-sourced software licensed under the MIT license. Designed and engineered by Alan Shaju (2026).
