Files
michaelschiemer/docs/claude/architecture.md
Michael Schiemer c93d3f07a2
All checks were successful
Test Runner / test-php (push) Successful in 31s
Deploy Application / deploy (push) Successful in 1m42s
Test Runner / test-basic (push) Successful in 7s
fix(Console): add void as valid return type for command methods
The MethodSignatureAnalyzer was rejecting command methods with void return
type, causing the schedule:run command to fail validation.
2025-11-26 06:16:09 +01:00

261 lines
8.1 KiB
Markdown

# Architecture
Architektur-Übersicht des Custom PHP Frameworks.
## Core Architectural Patterns
### Fundamentale Prinzipien
- **No Inheritance**: Komposition über Vererbung - `extends` komplett vermeiden
- **Immutable by Design**: Objekte sollten wann immer möglich unveränderlich sein
- **Readonly Everywhere**: Klassen und Properties `readonly` wo möglich
- **Final by Default**: Klassen sind `final` außer wenn explizit für Erweiterung designt
- **Explicit Dependency Injection**: Kein globaler State oder Service Locators
- **Modular Architecture**: Minimale externe Abhängigkeiten, klare Grenzen
- **Event-Driven Architecture**: Lose Kopplung durch Domain Events
- **Automatic Discovery**: Convention over Configuration mit Attribute Scanning
### Directory Structure
```
src/
├── Application/ # Anwendungsspezifische Controller und Logik
├── Domain/ # Domain Models und Business Logic
├── Framework/ # Framework Core Komponenten
│ └── Mcp/ # MCP Server und Tools für AI Integration
└── Infrastructure/ # Externe Service Integrationen
resources/ # Frontend Assets (CSS, JS)
public/ # Web-zugängliche Dateien
tests/ # Test Dateien
docs/ # Dokumentation
```
## Core Components
### Application Bootstrap
**`src/Framework/Core/Application.php`**
- Haupt-Anwendungsklasse die den Request-Lifecycle orchestriert
- Event-basierte Architektur für Anwendungs-Lifecycle
**`src/Framework/Core/AppBootstraper.php`**
- Bootstrapped die Anwendung und den DI Container
- Verwendet Event System für Lifecycle Management
**Events**: ApplicationBooted, BeforeHandleRequest, AfterHandleRequest
### Dependency Injection
**Container Interface**: `src/Framework/DI/Container.php`
**Default Implementation**: `src/Framework/DI/DefaultContainer.php`
**Features**:
- Binding, Singletons und Instance Registration
- Automatische Dependency Resolution
- Method Invocation mit Parameter Resolution
- Cached Reflection Provider für Performance
### HTTP & Routing
**Attribute-Based Routing** mit `#[Route]` Attributen:
```php
final readonly class ExampleController
{
#[Route(path: '/api/example', method: Method::GET)]
public function getExample(): JsonResult
{
return new JsonResult(['message' => 'Hello World']);
}
}
```
**Core Routing**: `src/Framework/Http/Middlewares/RoutingMiddleware.php`
- Middleware Chain Pattern für Request Processing
- Unterstützung verschiedener Result Types (JsonResult, ViewResult, Redirect, etc.)
### MCP Integration
**`src/Framework/Mcp/`** - Vollständige MCP Server Implementation
- `#[McpTool]` und `#[McpResource]` Attribute für AI Integration
- Automatische Discovery über Framework's Attribute System
- Sichere, projekt-beschränkte Dateisystem-Zugriffe für AI
```php
final readonly class FrameworkAnalyzer
{
#[McpTool(name: 'analyze_routes', description: 'Get all registered routes')]
public function analyzeRoutes(): array
{
return $this->compiledRoutes->getStaticRoutes();
}
}
```
## Advanced Systems
### Discovery System
**Automatic Attribute Scanning**:
- Eliminiert manuelle Konfiguration für Routes, Middleware und Commands
- Caching für Performance-Optimierung
- Unified Discovery Service für mehrere Attribute-Typen
### Database System
**EntityManager mit UnitOfWork Pattern**:
- Automatisches Change Tracking
- Bulk Operations für Performance
- Transaction Management mit Rollback Support
- Identity Mapping und Lazy Loading
**Schema Builder**:
- Database-agnostische Migrationen
- Fluent API für Schema-Definition
- Timestamp-basierte Migration Versionierung
- Support für MySQL, PostgreSQL, SQLite
**Connection Pooling**:
- Health Monitoring und automatische Recovery
- Retry Logic mit exponential Backoff
- Warmup Strategien für optimale Performance
### Event System
**Event Dispatcher** für Application Events:
- Verwendung für Application Lifecycle Management
- Domain Events für Business Logic
- Erweiterbare Event Handling Architektur
### Command/Query Bus Pattern
**`src/Framework/CommandBus/`** - Command/Query Handling
- Middleware Support für Command Processing
- Automatic Handler Discovery und Registration
### Performance Optimizations
**Route Compilation**:
- Compiled Routes mit separater Static/Dynamic Behandlung
- Route Parameter Extraction optimiert
- Pre-compiled Regex Patterns
**Caching System**:
- Multi-Level Caching für Attributes und Configuration
- Cached Reflection Provider für Dependency Injection
- Connection Pooling mit Retry Logic
## Value Objects System
**Extensive Use of Value Objects** statt primitiver Typen:
```php
// ❌ Keine Arrays oder Primitive verwenden
function processUser(array $user): array
// ✅ Value Objects verwenden
function processUser(User $user): UserProfile
```
**Available Value Objects**:
- Core: Email, RGBColor, Url, Hash, Version, Coordinates, ClassName, PhpNamespace
- HTTP: FlashMessage, ValidationError, RouteParameters
- Security: OWASPEventIdentifier, MaskedEmail, ThreatLevel
- Performance: Measurement, MetricContext, MemorySummary
- Filesystem: FilePath
- Framework: FrameworkModule, FrameworkModuleRegistry
## Framework Module System
Das Framework verwendet ein modulares System, bei dem jeder Top-Level-Ordner in `src/Framework/` als eigenständiges Modul behandelt wird.
### FrameworkModule Value Object
Repräsentiert ein einzelnes Framework-Modul:
```php
use App\Framework\Core\ValueObjects\FrameworkModule;
use App\Framework\Filesystem\ValueObjects\FilePath;
// Modul erstellen
$basePath = FilePath::create('/var/www/html/src/Framework');
$httpModule = FrameworkModule::create('Http', $basePath);
// Namespace-Zugehörigkeit prüfen
$namespace = PhpNamespace::fromString('App\\Framework\\Http\\Middlewares\\Auth');
$httpModule->containsNamespace($namespace); // true
// Klassen-Zugehörigkeit prüfen
$className = ClassName::create('App\\Framework\\Http\\Request');
$httpModule->containsClass($className); // true
// Relative Namespace ermitteln
$relative = $httpModule->getRelativeNamespace($namespace);
// Returns: PhpNamespace für 'Middlewares\\Auth'
```
### FrameworkModuleRegistry
Registry aller Framework-Module mit Lookup-Funktionalität:
```php
use App\Framework\Core\ValueObjects\FrameworkModuleRegistry;
// Automatische Discovery aller Module
$registry = FrameworkModuleRegistry::discover($frameworkPath);
// Oder manuell mit variadic constructor
$registry = new FrameworkModuleRegistry(
FrameworkModule::create('Http', $basePath),
FrameworkModule::create('Database', $basePath),
FrameworkModule::create('Cache', $basePath)
);
// Modul für Namespace finden
$module = $registry->getModuleForNamespace($namespace);
// Modul für Klasse finden
$module = $registry->getModuleForClass($className);
// Prüfen ob zwei Klassen im selben Modul liegen
$inSame = $registry->classesInSameModule($classA, $classB);
// Prüfen ob zwei Namespaces im selben Modul liegen
$inSame = $registry->inSameModule($namespaceA, $namespaceB);
// Prüfen ob zwei Dateien im selben Modul liegen
$inSame = $registry->filesInSameModule($filePathA, $filePathB);
```
### Use Cases
**Dependency Analysis**: Prüfen ob Abhängigkeiten zwischen Modulen bestehen
**Module Boundaries**: Sicherstellen dass Module-interne Klassen nicht extern verwendet werden
**Circular Dependency Detection**: Erkennen von zirkulären Modul-Abhängigkeiten
**Code Organization**: Validieren dass Klassen im richtigen Modul liegen
## Middleware System
**Priority-Based Middleware Chain**:
- `#[MiddlewarePriorityAttribute]` für Reihenfolge
- Request State Management zwischen Middleware
- Content Negotiation für flexible Responses
## Security Architecture
**Defense in Depth**:
- IP-based Authentication für Admin Routes
- Route Protection über Auth Attribute
- Input Validation und Sanitization
- CSRF Protection und Security Headers
- OWASP Security Event Logging
## Testing Architecture
**Mixed Testing Approach**:
- PHPUnit für traditionelle Tests
- Pest Framework für moderne Syntax
- Integration Tests für Web Controller
- Unit Tests für Domain Logic
- Test Files spiegeln Source Structure wider