Search by

cna / framework

Alan2k2

CnA Framework - Technical Architecture & Implementation

Package info

github.com/Alan2k2/CnA-Framework

Type:project

pkg:composer/cna/framework

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

dev-main 2026-11-07 11:45 UTC

This package is auto-updated.

Last update: 2026-11-07 23:25:46 UTC


README

CnA Framework Logo

The Contract-Driven PHP Framework
Secure โ€ข Scalable โ€ข Intelligent

Live Demo CI Status PHP Version License OWASP ASVS

๐ŸŒŸ 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

โšก 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:

  1. 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.
  2. First-Class N+1 Prevention & Query Observability:

    • Strict mode in development/testing throws LazyLoadingViolationException on unexpected dynamic lazy loading.
    • Fast $O(1)$ eager loading via Model::with(['user', 'items'])->get().
    • Built-in QueryObserver with normalized SQL fingerprinting, repeated relation query detection, and route/job query budgets.
  3. 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).
  4. Provider-Independent AI Subsystem:

    • Pluggable provider abstraction (AIProviderInterface, EmbeddingProviderInterface, TokenCounterInterface).
    • Built-in FakeAIProvider for 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.
  5. Turnkey CLI Experience (php cna or ./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

๐Ÿ“‚ 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).