src/
├── CLI/ # Command-line interface & code generation
├── core/ # Core framework classes (Bootstrap, ApiService, Security)
├── http/ # HTTP layer (Request, Response, JWT)
├── database/ # Database layer (ORM, migrations, query builders)
├── helper/ # Utility classes (TypeChecker, FileHelper, CryptHelper)
├── startup/ # Platform-specific initialization files
└── stubs/ # IDE type stubs (OpenSwoole, Redis)
app/folder code never changes when switching webservers- Framework handles all platform differences
- Same API endpoints work on Apache, OpenSwoole, and Nginx
- No configuration needed - Security works out of the box
- Path protection, input sanitization, SQL injection prevention all automatic
- Developers only call
definePostSchema()andauth()methods
- Automatic webserver detection (
WebserverDetector) - Automatic database manager selection (
DatabaseManagerFactory) - Automatic request adapter selection (
ApacheRequestvsSwooleRequest)
- Generate Services, Controllers, Models, Tables, CRUD operations
- Template-based generation system
- Docker-compose generation with optional services
HTTP Request
↓
index.php (startup/apache/index.php)
↓
Bootstrap.php → APM initialized (early tracing) → Security check (automatic)
↓
ApacheRequest.php → Sanitize all inputs (automatic)
↓
app/api/User.php → Developer schema validation (optional)
↓
UserController.php → Business logic (traced if APM_TRACE_CONTROLLER=1)
↓
UserTable.php → Database operations (traced if APM_TRACE_DB_QUERY=1, prepared statements - automatic)
↓
JsonResponse.php → Return JSON
↓
APM traces sent (fire-and-forget, non-blocking)
HTTP Request
↓
OpenSwooleServer.php → Security check (automatic)
↓
SwooleRequest.php → Sanitize all inputs (automatic)
↓
SwooleBootstrap.php → APM initialized (early tracing) → Route to API service
↓
app/api/User.php → Developer schema validation (optional)
↓
UserController.php → Business logic (traced if APM_TRACE_CONTROLLER=1)
↓
UserTable.php → Database operations (traced if APM_TRACE_DB_QUERY=1, connection pooling - automatic)
↓
JsonResponse.php → Return JSON (via showSwoole())
↓
APM traces sent (fire-and-forget, non-blocking)
Command.php- Base command classAbstractInit.php- Template method for project initializationInitProject.php- Main init orchestratorInitApache.php/InitSwoole.php- Platform-specific initCreateService.php,CreateController.php, etc. - Code generatorsDockerComposeInit.php- Docker setup wizard
Key Features:
- Template-based code generation
- Interactive project setup
- Database migration commands
- File system management with overwrite protection
Bootstrap.php/SwooleBootstrap.php- Request routing, APM initialization (early tracing)ApiService.php/SwooleApiService.php- Base API service classescallController()method for automatic controller tracing- Uses
$request->apmfor trace context propagation
Controller.php- Base controller with pagination, filtering, sanitizationcreateModel()helper for automatic Request propagation- Uses
$request->apmfor trace context
ApmTracingTrait.php- Unified APM tracing methods (reusable across layers)SecurityManager.php- Path access protectionWebserverDetector.php- Environment detection (cached)OpenSwooleServer.php- OpenSwoole server lifecycleHotReloadManager.php- Development hot reload (watches app dir only via ProjectHelper; dev-only; 5s interval)RedisManager.php- Redis connection singletonApiDocGenerator.php- Auto-generate API documentation
Key Features:
- Automatic security enforcement
- Environment-aware routing
- Developer-friendly base classes
- Built-in documentation generation
- Native APM integration - Automatic tracing with zero configuration
- Early APM initialization in Bootstrap/SwooleBootstrap
- Controller tracing via
callController()(environment-controlled) - Database query tracing (environment-controlled)
- Trace context propagation through all layers
Request.php- Unified request object (all inputs sanitized)ApacheRequest.php- Apache request adapter (sanitizes headers + inputs)SwooleRequest.php- OpenSwoole request adapter (sanitizes headers + inputs)Response.php- Response factoryJsonResponse.php- JSON response handler (show() vs showSwoole())JWTToken.php- JWT creation, verification, renewalNoCors.php- CORS handlerSwooleWebSocketHandler.php- WebSocket support
Key Features:
- Automatic input sanitization (XSS prevention)
- Automatic header sanitization (injection prevention)
- Cookie filtering (dangerous cookie blocking)
- JWT authentication/authorization
- Schema validation (mass assignment prevention)
Table.php- Main ORM class (fluent interface)setRequest()method for APM trace context propagation
UniversalQueryExecuter.php- Enforces prepared statements- APM query tracing (if
APM_TRACE_DB_QUERY=1) - Captures query type, execution time, rows affected
- Uses
$request->apmfor trace context
- APM query tracing (if
ConnectionManager.php- Connection managementsetRequest()method for Request propagation
PdoQuery.php- PDO query wrappersetRequest()method for Request propagation
DatabaseManagerFactory.php- Auto-selects DB managerSwooleDatabaseManager.php- Connection pooling (OpenSwoole)SimplePdoDatabaseManager.php- Standard PDO (Apache/Nginx)EnhancedPdoDatabaseManager.php- Persistent PDO (optional)QueryBuilder.php- Lower-level query builderSchema.php/SchemaGenerator.php- Schema managementTableGenerator.php- Table class generation
Key Features:
- 100% SQL injection prevention (all queries use prepared statements)
- Connection pooling for OpenSwoole (performance)
- Environment-aware connection management
- Migration system
- Schema generation
- APM query tracing - Automatic spans for all database queries (optional)
TypeChecker.php- Runtime type validation (advanced options)ProjectHelper.php- Path resolution (finds composer.lock), env/base URL/system paths, APM detection,disableOpcacheIfDev()for devFileHelper.php- File operations + encryptionImageHelper.php- Image processing + signature detectionCryptHelper.php- Password hashing (Argon2I) + AES-256-CBC encryptionStringHelper.php- String manipulation utilitiesTypeHelper.php- Type utilities (guid, timestamp, etc.)JsonHelper.php- JSON validationWebHelper.php- Webserver detectionChatGptClient.php- OpenAI integrationServerMonitorHelper.php- Server resource monitoring (RAM, CPU)NetworkHelper.php- Network statistics collection
Key Features:
- File signature detection (MIME type verification)
- File encryption (AES-256-CBC + HMAC)
- Password security (Argon2I)
- Type validation (email, string length, regex, dates, etc.)
- Server monitoring (cross-platform RAM, CPU, network metrics)
startup/
├── apache/ # Apache-specific files
│ ├── index.php # Apache entry point
│ ├── appIndex.php # Application bootstrap
│ ├── composer.json # Apache dependencies
│ └── docker-compose.yml
├── swoole/ # OpenSwoole-specific files
│ ├── index.php # OpenSwoole entry point
│ ├── appIndex.php # Application bootstrap
│ ├── composer.json # OpenSwoole dependencies (Hyperf)
│ └── docker-compose.yml
├── nginx/ # Nginx files (coming soon)
└── common/ # Shared files for all platforms
└── user/ # Example User files
Key Features:
- Platform-specific entry points
- Platform-specific dependencies
- Shared common files
- Docker configurations
- ✅ Path Protection - Blocks
/app,/vendor,.env, etc. - ✅ Header Sanitization - All HTTP headers sanitized
- ✅ Input Sanitization - All GET/POST/PUT/PATCH sanitized (XSS prevention)
- ✅ SQL Injection Prevention - All queries use prepared statements
- ✅ File Name Sanitization - Uploaded file names sanitized
- ✅ Cookie Filtering - Dangerous cookies blocked
- ⚙️ Schema Validation - Call
definePostSchema()(prevents mass assignment) - ⚙️ Authentication - Call
$request->auth()(JWT validation) - ⚙️ Authorization - Call
$request->auth(['role'])(role checking) - ⚙️ File Signature Detection - Use
ImageHelpermethods - ⚙️ File Encryption - Use
FileHelper::encrypt()
- ✅ Root Trace - Automatically created in Bootstrap/SwooleBootstrap
- Captures full request lifecycle
- Initialized early (before routing)
- Stored in
$request->apmfor trace context propagation
- ✅ Exception Tracking - All exceptions automatically recorded
- ✅ Trace Context Propagation - All spans share the same
traceId- Bootstrap → ApiService → Controller → Table → UniversalQueryExecuter
- ✅ Fire-and-Forget Pattern - Traces sent after HTTP response (non-blocking)
- ⚙️ Controller Tracing - Enable via
APM_TRACE_CONTROLLER=1- Use
callController()in API services - Automatic spans for controller method calls
- Captures method name, response code, execution time
- Use
- ⚙️ Database Query Tracing - Enable via
APM_TRACE_DB_QUERY=1- Use
createModel()in controllers (sets Request on models) - Automatic spans for all SQL queries
- Captures query type, execution time, rows affected, SQL statement
- Use
Bootstrap/SwooleBootstrap
↓ (APM initialized, root trace started)
↓ ($request->apm set)
ApiService
↓ (uses $request->apm)
↓ (callController() creates controller span if enabled)
Controller
↓ (uses $request->apm)
↓ (createModel() sets Request on model)
Table → ConnectionManager → PdoQuery
↓ (Request propagated through all layers)
UniversalQueryExecuter
↓ (uses $request->apm for query span if enabled)
Database Query Executed
↓
Response Sent
↓
APM Traces Sent (fire-and-forget, non-blocking)
Bootstrap.php/SwooleBootstrap.php- Early APM initializationApiService::callController()- Controller tracing proxyController::createModel()- Request propagation helperTable::setRequest()- Request propagation to database layerUniversalQueryExecuter- Database query tracingApmTracingTrait- Unified tracing methods for custom spans
- Works with any APM provider via
gemvc/apm-contractspackage - TraceKit (
gemvc/apm-tracekit) - Datadog, New Relic, Elastic APM (custom providers)
- Provider-agnostic design
- Zero overhead when disabled - Environment flags control tracing
- Minimal overhead when enabled - ~0.25ms per request
- Non-blocking - Traces sent after HTTP response
- Sample rate support - Control trace volume via
TRACEKIT_SAMPLE_RATE
- Connection pooling (database)
- Persistent processes (no PHP bootstrap overhead)
- Hot reload (development)
- Async capabilities
- WebSocket support
- Optional persistent PDO connections (
DB_ENHANCED_CONNECTION=1) - Cached environment detection
- Singleton patterns for managers
- Prepared statement reuse
URL: /api/User/create
↓
Extracts: Service = "User", Method = "create"
↓
Loads: app/api/User.php
↓
Calls: User::create()
↓
User::create() validates schema → delegates to UserController
↓
UserController::create() handles business logic
↓
UserTable::create() performs database operation
Configuration (via .env):
SERVICE_IN_URL_SECTION=1(default: 1)METHOD_IN_URL_SECTION=2(default: 2)
- Template Method -
AbstractInit.php→InitApache.php/InitSwoole.php - Strategy -
DatabaseManagerFactory→ Different DB managers - Factory -
DatabaseManagerFactory,Responsefactory - Adapter -
ApacheRequest,SwooleRequestadapt to unifiedRequest - Singleton -
RedisManager, cachedDatabaseManagerFactory - Builder -
Tablefluent interface,QueryBuilder - Dependency Injection -
Requestinjected into services/controllers
gemvc init- Initialize new project (select webserver)gemvc create:service- Generate API servicegemvc create:controller- Generate controllergemvc create:model- Generate modelgemvc create:table- Generate table classgemvc create:crud- Generate full CRUD
gemvc db:init- Initialize databasegemvc db:migrate- Run migrationsgemvc db:list- List tablesgemvc db:describe- Describe table structuregemvc db:drop- Drop tablegemvc db:unique- Add unique constraint
gemvc docker:init- Generate docker-compose.yml
startup/apache/index.php- Apache entrystartup/swoole/index.php- OpenSwoole entrybin/gemvc- CLI entry point
src/core/Bootstrap.php- Apache request routersrc/core/SwooleBootstrap.php- OpenSwoole request routersrc/core/OpenSwooleServer.php- OpenSwoole server managersrc/http/Request.php- Unified request objectsrc/database/Table.php- Main ORM class
src/core/SecurityManager.php- Path protectionsrc/http/ApacheRequest.php- Input sanitization (Apache)src/http/SwooleRequest.php- Input sanitization (OpenSwoole)src/database/UniversalQueryExecuter.php- SQL injection prevention
GEMVC is a production-ready, multi-platform PHP REST API framework that:
✅ Automatically secures 90% of common vulnerabilities
✅ Works identically on Apache, OpenSwoole, and Nginx
✅ Generates code via CLI commands
✅ Prevents SQL injection with 100% prepared statement coverage
✅ Sanitizes all inputs automatically (XSS prevention)
✅ Provides JWT authentication out of the box
✅ Native APM integration - Automatic performance monitoring with zero configuration
✅ Supports WebSockets on OpenSwoole
✅ Includes hot reload for development
✅ Auto-generates API docs from docblocks
✅ Manages database with migrations and schema generation
Result: Developers write clean, secure API code without worrying about webserver differences or most security concerns!