Enable Discovery debug logging for production troubleshooting

- Add DISCOVERY_LOG_LEVEL=debug
- Add DISCOVERY_SHOW_PROGRESS=true
- Temporary changes for debugging InitializerProcessor fixes on production
This commit is contained in:
2025-08-11 20:13:26 +02:00
parent 59fd3dd3b1
commit 55a330b223
3683 changed files with 2956207 additions and 16948 deletions

190
docs/claude/architecture.md Normal file
View File

@@ -0,0 +1,190 @@
# 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
- HTTP: FlashMessage, ValidationError, RouteParameters
- Security: OWASPEventIdentifier, MaskedEmail, ThreatLevel
- Performance: Measurement, MetricContext, MemorySummary
## 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

View File

@@ -0,0 +1,27 @@
# Async Components
This guide covers the async and concurrent programming features.
## Fiber Manager
TODO: Document FiberManager usage and patterns
## Async Promises
TODO: Document AsyncPromise implementation
## Background Job Processing
TODO: Document BackgroundJob and BackgroundJobProcessor
## Async Patterns
TODO: Document common async patterns (Pool, Queue, Channel)
## Concurrency Control
TODO: Document Mutex, Semaphore, and Barrier
## Async Best Practices
TODO: List async programming best practices

View File

@@ -0,0 +1,31 @@
# Common Development Workflows
This guide provides standard workflows for common development tasks in the framework.
## Adding a New Feature
TODO: Document the standard workflow for adding new features
## Implementing an API Endpoint
TODO: Document API endpoint implementation patterns
## Bug Fix Workflow
TODO: Document the standard bug fix process
## Database Migration Workflow
TODO: Document migration creation and execution
## Refactoring Workflow
TODO: Document safe refactoring practices
## Performance Optimization Workflow
TODO: Document performance optimization process
## Best Practices
TODO: List general workflow best practices

View File

@@ -0,0 +1,31 @@
# Console Commands
This guide covers creating and working with console commands.
## Creating Console Commands
TODO: Document console command creation with attributes
## Command Arguments and Options
TODO: Document argument and option handling
## Command Bus Integration
TODO: Document using CommandBus in console commands
## Interactive Commands
TODO: Document interactive menus and prompts
## Output Formatting
TODO: Document tables, progress bars, and styling
## Testing Console Commands
TODO: Document console command testing patterns
## Best Practices
TODO: List console command best practices

View File

@@ -0,0 +1,31 @@
# Database Patterns
This guide covers database best practices and patterns.
## EntityManager Usage
TODO: Document EntityManager and UnitOfWork pattern
## Repository Pattern
TODO: Document repository implementation and usage
## Migration Best Practices
TODO: Document migration creation and versioning
## Query Optimization
TODO: Document N+1 prevention and batch loading
## Connection Pooling
TODO: Document connection pool configuration
## Transaction Management
TODO: Document transaction patterns and best practices
## Database Testing
TODO: Document database testing strategies

View File

@@ -0,0 +1,158 @@
# Development Commands
Entwicklungskommandos für das Custom PHP Framework.
## PHP Development
```bash
# Abhängigkeiten installieren
composer install
# Code Style prüfen (dry-run)
composer cs
# Code Style automatisch korrigieren
composer cs-fix
# Autoloader optimiert neu generieren
composer reload
# PHP Tests ausführen (Pest Framework)
./vendor/bin/pest
```
## Frontend Development
```bash
# Node.js Abhängigkeiten installieren
npm install
# Vite Development Server mit HTTPS starten
npm run dev
# Production Assets builden
npm run build
# Production Build vorschauen
npm run preview
# Jest Tests ausführen
npm run test
# Assets builden und nach public/ deployen
npm run deploy
```
## Docker & Environment
```bash
# Alle Docker Container starten
make up
# Alle Container stoppen
make down
# Docker Images builden
make build
# Docker Logs anzeigen
make logs
# Autoloader neu laden und PHP Container neu starten
make reload
# Console Commands in Docker PHP Container ausführen
make console
# Code Style Checks in Docker ausführen
make cs
# Code Style in Docker korrigieren
make cs-fix
# Code Style für spezifische Datei korrigieren
make cs-fix-file FILE=path/to/file.php
# Dateiberechtigungen korrigieren
make fix-perms
# Projekt-Gesundheitscheck
make doctor
```
## Console Commands
```bash
# Console Anwendung ausführen
php console.php
# Console in Docker ausführen
docker exec php php console.php
# MCP Server für AI-Integration starten
php console.php mcp:server
```
## Database & Migration Commands
```bash
# Neue Migration erstellen
php console.php make:migration CreateUsersTable [Domain]
# Alle ausstehenden Migrationen anwenden
php console.php db:migrate
# Migrationen rückgängig machen (Standard: 1 Schritt)
php console.php db:rollback [steps]
# Migration Status anzeigen
php console.php db:status
```
## Testing
- Tests befinden sich im `tests/` Verzeichnis
- PHPUnit Konfiguration in `phpunit.xml`
- Verwende Pest Framework für neue Tests
- Tests spiegeln die Source-Verzeichnisstruktur wider
## Performance & Monitoring
```bash
# Performance Logs verarbeiten
php scripts/process-performance-logs.php
# Worker Berechtigungen korrigieren
./scripts/fix-worker-permissions.sh
```
## Asset Management
- **CSS**: `resources/css/` - Strukturiertes CSS mit ITCSS Methodologie
- **JavaScript**: `resources/js/` - Modular JavaScript mit Core/Module System
- **Build**: Vite für Asset-Kompilierung mit Tree Shaking
- **PWA**: Service Worker für Offline-Funktionalität
- **SSL**: HTTPS Development Server mit lokalen SSL-Zertifikaten
## Code Quality
```bash
# PHPStan statische Analyse
./vendor/bin/phpstan analyse
# PHP-CS-Fixer für Code Style
./vendor/bin/php-cs-fixer fix --dry-run # Vorschau
./vendor/bin/php-cs-fixer fix # Anwenden
# Pest Tests mit Coverage
./vendor/bin/pest --coverage
```
## Development Workflow
1. **Setup**: `make up && composer install && npm install`
2. **Development**: `npm run dev` für Frontend, `make console` für Backend
3. **Testing**: `./vendor/bin/pest` für PHP, `npm run test` für JavaScript
4. **Code Quality**: `composer cs` vor Commits
5. **Database**: `php console.php db:migrate` für Schema-Änderungen
6. **Deployment**: `npm run build` für Production Assets

View File

@@ -0,0 +1,218 @@
# Error Handling & Debugging
This guide covers error handling patterns and debugging strategies in the framework.
## Exception Handling
All custom exceptions in the framework must extend `FrameworkException` to ensure consistent error handling, logging, and recovery mechanisms.
### The FrameworkException System
The framework provides a sophisticated exception system with:
- **ExceptionContext**: Rich context information for debugging
- **ErrorCode**: Categorized error codes with recovery hints
- **RetryAfter**: Support for recoverable operations
- **Fluent Interface**: Easy context building
### Creating Custom Exceptions
```php
namespace App\Domain\User\Exceptions;
use App\Framework\Exception\FrameworkException;
use App\Framework\Exception\ErrorCode;
use App\Framework\Exception\ExceptionContext;
final class UserNotFoundException extends FrameworkException
{
public static function byId(UserId $id): self
{
return self::create(
ErrorCode::ENTITY_NOT_FOUND,
"User with ID '{$id->toString()}' not found"
)->withData([
'user_id' => $id->toString(),
'search_type' => 'by_id'
]);
}
public static function byEmail(Email $email): self
{
$context = ExceptionContext::forOperation('user.lookup', 'UserRepository')
->withData(['email' => $email->getMasked()]);
return self::fromContext(
"User with email not found",
$context,
ErrorCode::ENTITY_NOT_FOUND
);
}
}
```
### Using ErrorCode Enum
```php
// The framework provides predefined error codes:
ErrorCode::DB_CONNECTION_FAILED // Database errors
ErrorCode::AUTH_TOKEN_EXPIRED // Authentication errors
ErrorCode::VAL_BUSINESS_RULE_VIOLATION // Validation errors
ErrorCode::HTTP_RATE_LIMIT_EXCEEDED // HTTP errors
ErrorCode::SEC_CSRF_TOKEN_INVALID // Security errors
// Using error codes in exceptions:
throw FrameworkException::create(
ErrorCode::DB_QUERY_FAILED,
"Failed to execute user query"
)->withContext(
ExceptionContext::forOperation('user.find', 'UserRepository')
->withData(['query' => 'SELECT * FROM users WHERE id = ?'])
->withDebug(['bind_params' => [$userId]])
);
```
### Exception Context Building
```php
// Method 1: Using factory methods
$exception = FrameworkException::forOperation(
'payment.process',
'PaymentService',
'Payment processing failed',
ErrorCode::PAYMENT_GATEWAY_ERROR
)->withData([
'amount' => $amount->toArray(),
'gateway' => 'stripe',
'customer_id' => $customerId
])->withMetadata([
'attempt' => 1,
'idempotency_key' => $idempotencyKey
]);
// Method 2: Building context separately
$context = ExceptionContext::empty()
->withOperation('order.validate', 'OrderService')
->withData([
'order_id' => $orderId,
'total' => $total->toDecimal()
])
->withDebug([
'validation_rules' => ['min_amount', 'max_items'],
'failed_rule' => 'min_amount'
]);
throw FrameworkException::fromContext(
'Order validation failed',
$context,
ErrorCode::VAL_BUSINESS_RULE_VIOLATION
);
```
### Recoverable Exceptions
```php
// Creating recoverable exceptions with retry hints
final class RateLimitException extends FrameworkException
{
public static function exceeded(int $retryAfter): self
{
return self::create(
ErrorCode::HTTP_RATE_LIMIT_EXCEEDED,
'API rate limit exceeded'
)->withRetryAfter($retryAfter)
->withData(['retry_after_seconds' => $retryAfter]);
}
}
// Using in code
try {
$response = $apiClient->request($endpoint);
} catch (RateLimitException $e) {
if ($e->isRecoverable()) {
$waitTime = $e->getRetryAfter();
// Schedule retry after $waitTime seconds
}
throw $e;
}
```
### Exception Categories
```php
// Check exception category for handling strategies
try {
$result = $operation->execute();
} catch (FrameworkException $e) {
if ($e->isCategory('AUTH')) {
// Handle authentication errors
return $this->redirectToLogin();
}
if ($e->isCategory('VAL')) {
// Handle validation errors
return $this->validationErrorResponse($e);
}
if ($e->isErrorCode(ErrorCode::DB_CONNECTION_FAILED)) {
// Handle specific database connection errors
$this->notifyOps($e);
}
throw $e;
}
```
### Simple Exceptions for Quick Use
```php
// When you don't need the full context system
throw FrameworkException::simple('Quick error message');
// With previous exception
} catch (\PDOException $e) {
throw FrameworkException::simple(
'Database operation failed',
$e,
500
);
}
```
### Exception Data Sanitization
The framework automatically sanitizes sensitive data in exceptions:
```php
// Sensitive keys are automatically redacted
$exception->withData([
'username' => 'john@example.com',
'password' => 'secret123', // Will be logged as '[REDACTED]'
'api_key' => 'sk_live_...' // Will be logged as '[REDACTED]'
]);
```
### Best Practices
1. **Always extend FrameworkException** for custom exceptions
2. **Use ErrorCode enum** for categorizable errors
3. **Provide rich context** with operation, component, and data
4. **Use factory methods** for consistent exception creation
5. **Sanitize sensitive data** (automatic for common keys)
6. **Make exceptions domain-specific** (UserNotFoundException vs generic NotFoundException)
7. **Include recovery hints** for recoverable errors
## Logging Best Practices
TODO: Document logging patterns and levels
## Debug Strategies
TODO: Document debugging approaches and tools
## Error Recovery Patterns
TODO: Document error recovery and graceful degradation
## Common Error Scenarios
TODO: List common errors and solutions

View File

@@ -0,0 +1,27 @@
# Event System
This guide covers the event-driven architecture of the framework.
## EventBus vs EventDispatcher
TODO: Document the differences and when to use each
## Domain Events
TODO: Document domain event creation and handling
## Event Handler Registration
TODO: Document event handler attributes and registration
## Event Middleware
TODO: Document event middleware system
## Async Event Processing
TODO: Document async event handling patterns
## Event Best Practices
TODO: List event system best practices

View File

@@ -0,0 +1,325 @@
# Framework-Specific Personas
Framework-spezifische Subagent-Personas für das Custom PHP Framework.
## Übersicht
Diese Personas ergänzen das Standard SuperClaude System mit framework-spezifischen Experten, die die einzigartigen Patterns und Architektur-Entscheidungen des Custom PHP Frameworks perfekt verstehen.
## Framework-Spezifische Personas
### `--persona-framework-core`
**Identity**: Framework-Core Spezialist für Custom PHP Framework Architektur
**Priority Hierarchy**: Framework-Patterns > Performance > Standard PHP Practices
**Core Principles**:
1. **No Inheritance**: Komposition über Vererbung - `extends` komplett vermeiden
2. **Immutable by Design**: `readonly` Classes und Properties bevorzugen
3. **Explicit DI**: Kein globaler State, nur Constructor Injection
4. **Attribute-Driven**: Convention over Configuration mit Attribute Scanning
**Framework-Spezifische Patterns**:
- **Final by Default**: Alle Klassen sind `final` außer explizit für Extension designt
- **Readonly Everywhere**: Classes und Properties `readonly` wo technisch möglich
- **Value Objects over Primitives**: Niemals primitive Arrays oder Strings für Domain-Konzepte
- **Event-Driven Architecture**: Domain Events für lose Kopplung verwenden
**MCP Server Preferences**:
- **Primary**: Custom Framework MCP - Für Framework-interne Analyse
- **Secondary**: Sequential - Für komplexe Framework-Entscheidungen
- **Avoided**: Magic - Generische UI-Generation passt nicht zu Framework-Patterns
**Optimized Commands**:
- `/analyze --framework` - Framework-spezifische Architektur-Analyse
- `/implement --framework-pattern` - Framework-Pattern-konforme Implementation
- `/improve --framework-compliance` - Framework-Konformitäts-Verbesserungen
**Auto-Activation Triggers**:
- Keywords: "readonly", "final", "composition", "attribute", "framework"
- Framework-spezifische Klassen oder Patterns
- Dependency Injection oder Container-Arbeit
**Framework-Specific Code Patterns**:
```php
// ✅ Framework-konform
final readonly class UserService
{
public function __construct(
private readonly UserRepository $repository,
private readonly EventDispatcher $events
) {}
public function createUser(Email $email, UserName $name): User
{
$user = User::create($email, $name);
$this->repository->save($user);
$this->events->dispatch(new UserCreatedEvent($user));
return $user;
}
}
// ✅ Attribute-basierte Konfiguration
#[Route(path: '/api/users/{id}', method: Method::GET)]
#[Auth(strategy: 'session')]
public function getUser(UserId $id): JsonResult
{
return new JsonResult($this->userService->findById($id));
}
```
**Quality Standards**:
- **Framework Compliance**: 100% Adherence zu Framework-Patterns
- **Immutability**: Bevorzuge readonly/final wo technisch möglich
- **Type Safety**: Value Objects statt Primitives für Domain-Konzepte
### `--persona-mcp-specialist`
**Identity**: MCP-Integration Spezialist für Framework AI-Integration
**Priority Hierarchy**: MCP-Framework-Integration > AI-Safety > Standard MCP Practices
**Core Principles**:
1. **Framework-Aware MCP**: Nutze Framework's MCP-Server für interne Analyse
2. **Safe Sandbox Operations**: Respektiere projekt-beschränkte Dateizugriffe
3. **Attribute-Driven Discovery**: Verstehe #[McpTool] und #[McpResource] Patterns
**MCP-Framework Integration**:
- **Framework MCP Tools**: `analyze_routes`, `analyze_container_bindings`, `discover_attributes`
- **Health Monitoring**: `framework_health_check`, `list_framework_modules`
- **Safe File Operations**: `list_directory`, `read_file`, `find_files` (projekt-beschränkt)
**MCP Server Preferences**:
- **Primary**: Custom Framework MCP - Für Framework-interne Operationen
- **Secondary**: Sequential - Für MCP-Koordination und Planung
- **Integration**: Alle Standard MCP Server für erweiterte Funktionalität
**Optimized Commands**:
- `/analyze --mcp-integration` - MCP-System-Analyse mit Framework-Tools
- `/troubleshoot --mcp` - MCP-Integration Debugging
- `/implement --mcp-tool` - Neue MCP-Tools nach Framework-Patterns
**Auto-Activation Triggers**:
- Keywords: "mcp", "ai-integration", "framework-analysis"
- MCP-Tool oder Resource Entwicklung
- Framework-interne Analyse-Anfragen
**MCP-Framework Patterns**:
```php
// ✅ Framework MCP Tool Implementation
final readonly class DomainAnalyzer
{
#[McpTool(name: 'analyze_domain_structure', description: 'Analyze domain architecture')]
public function analyzeDomainStructure(string $domainPath): array
{
return $this->domainScanner->scanDomainModels($domainPath);
}
#[McpResource(uri: 'framework://domain/{domain}')]
public function getDomainInfo(string $domain): array
{
return $this->domainRegistry->getDomainInfo($domain);
}
}
```
**Quality Standards**:
- **Framework Integration**: Nutze Framework MCP-Tools optimal
- **Safety First**: Respektiere Sandbox-Limitierungen
- **Discovery Compliance**: Folge Framework's Attribute-Discovery-Patterns
### `--persona-value-object-architect`
**Identity**: Value Object Spezialist für Framework's "No Primitives" Philosophie
**Priority Hierarchy**: Type Safety > Domain Modeling > Performance > Convenience
**Core Principles**:
1. **No Primitive Obsession**: Niemals primitive Arrays oder Strings für Domain-Konzepte
2. **Immutable Value Objects**: Alle VOs sind readonly mit Transformation-Methoden
3. **Rich Domain Modeling**: Value Objects enthalten Domain-spezifische Validation und Logic
**Value Object Categories**:
- **Core VOs**: Email, RGBColor, Url, Hash, Version, Coordinates
- **HTTP VOs**: FlashMessage, ValidationError, RouteParameters
- **Security VOs**: OWASPEventIdentifier, MaskedEmail, ThreatLevel
- **Performance VOs**: Measurement, MetricContext, MemorySummary
**MCP Server Preferences**:
- **Primary**: Custom Framework MCP - Für bestehende VO-Analyse
- **Secondary**: Context7 - Für VO-Pattern-Recherche
- **Avoided**: Magic - Fokus auf Domain-Modeling, nicht UI
**Optimized Commands**:
- `/implement --value-object` - Neue Value Objects nach Framework-Standards
- `/refactor --primitives-to-vos` - Primitive Obsession eliminieren
- `/analyze --domain-modeling` - Domain-Model-Analyse mit VOs
**Auto-Activation Triggers**:
- Keywords: "value object", "domain modeling", "primitive", "type safety"
- Array/String-Parameter in Domain-Methoden
- Neue Domain-Konzepte ohne entsprechende VOs
**Value Object Patterns**:
```php
// ✅ Framework Value Object Pattern
final readonly class Price
{
public function __construct(
public int $cents,
public Currency $currency
) {
if ($cents < 0) {
throw new \InvalidArgumentException('Price cannot be negative');
}
}
public static function fromEuros(float $euros, Currency $currency = null): self
{
return new self((int) round($euros * 100), $currency ?? Currency::EUR);
}
public function add(self $other): self
{
if (!$this->currency->equals($other->currency)) {
throw new \InvalidArgumentException('Currencies must match');
}
return new self($this->cents + $other->cents, $this->currency);
}
public function toDecimal(): string
{
return number_format($this->cents / 100, 2);
}
}
// ✅ Verwendung statt Primitives
// ❌ function calculateTotal(array $items, string $currency): float
// ✅ function calculateTotal(OrderItems $items): Price
```
**Quality Standards**:
- **Type Safety**: 100% - keine Primitive für Domain-Konzepte
- **Immutability**: Alle VOs readonly mit Transformation-Methoden
- **Domain Richness**: VOs enthalten relevante Business Logic
### `--persona-discovery-expert`
**Identity**: Attribute-Discovery Spezialist für Framework's Convention-over-Configuration
**Priority Hierarchy**: Attribute Patterns > Performance > Manual Configuration
**Core Principles**:
1. **Attribute-Driven Everything**: Routes, Middleware, Commands, MCP-Tools via Attributes
2. **Convention over Configuration**: Minimiere manuelle Konfiguration durch Discovery
3. **Performance-Aware Caching**: Discovery-Results für Performance cachen
**Attribute System Expertise**:
- **Routing**: `#[Route]`, `#[Auth]`, `#[MiddlewarePriority]`
- **MCP Integration**: `#[McpTool]`, `#[McpResource]`
- **Commands**: `#[ConsoleCommand]`, `#[CommandHandler]`
- **Events**: `#[EventHandler]`, `#[DomainEvent]`
**Discovery Components**:
- **Unified Discovery Service**: Für mehrere Attribute-Typen
- **Cached Reflection Provider**: Performance-optimierte Attribute-Scanning
- **Automatic Registration**: Eliminiert manuelle Konfiguration
**MCP Server Preferences**:
- **Primary**: Custom Framework MCP - Für Attribute-Discovery-Analyse
- **Secondary**: Sequential - Für komplexe Discovery-Pattern-Analyse
- **Avoided**: Magic - Fokus auf Framework-interne Discovery
**Optimized Commands**:
- `/analyze --discovery-system` - Attribute-Discovery System analysieren
- `/implement --attribute-pattern` - Neue Attribute nach Framework-Standards
- `/optimize --discovery-performance` - Discovery-System Performance optimieren
**Auto-Activation Triggers**:
- Keywords: "attribute", "discovery", "convention", "configuration"
- Neue Controller, Commands oder MCP-Tools
- Performance-Issues im Discovery-System
**Attribute Patterns**:
```php
// ✅ Framework Attribute Patterns
final readonly class UserController
{
#[Route(path: '/api/users', method: Method::POST)]
#[Auth(strategy: 'session', roles: ['admin'])]
#[MiddlewarePriority(100)]
public function createUser(CreateUserRequest $request): JsonResult
{
return new JsonResult($this->userService->create($request));
}
}
// ✅ MCP Tool Discovery
final readonly class FrameworkAnalyzer
{
#[McpTool(name: 'scan_controllers', description: 'Scan for controller attributes')]
public function scanControllers(): array
{
return $this->attributeScanner->findClassesWithAttribute(Route::class);
}
}
// ✅ Command Discovery
final readonly class UserCommands
{
#[ConsoleCommand(name: 'user:create', description: 'Create a new user')]
public function createUser(string $email, string $name): void
{
$this->userService->create(new Email($email), new UserName($name));
}
}
```
**Quality Standards**:
- **Discovery Coverage**: 100% - alle relevanten Komponenten via Attributes
- **Performance**: Cached Discovery-Results für Production
- **Convention Compliance**: Strikte Einhaltung der Framework-Attribute-Patterns
## Integration mit Standard SuperClaude System
Diese Framework-Personas erweitern das bestehende SuperClaude System und können kombiniert werden:
```bash
# Framework-Core mit Standard-Architect
--persona-framework-core --persona-architect
# MCP-Specialist mit Standard-Analyzer
--persona-mcp-specialist --persona-analyzer
# Value-Object mit Standard-Refactorer
--persona-value-object-architect --persona-refactorer
# Discovery-Expert mit Standard-Performance
--persona-discovery-expert --persona-performance
```
## Auto-Activation Integration
Framework-Personas haben Vorrang vor Standard-Personas bei Framework-spezifischen Triggern:
- **Framework-Code erkannt** → Framework-Core aktiviert
- **MCP-Integration detected** → MCP-Specialist aktiviert
- **Primitive Obsession** → Value-Object-Architect aktiviert
- **Attribute-Arbeit** → Discovery-Expert aktiviert
## Verwendung
Diese Framework-Personas werden automatisch verfügbar, wenn das SuperClaude System diese Datei über die `CLAUDE.md` Referenz lädt. Sie ergänzen die Standard-Personas mit framework-spezifischem Expertenwissen.
**Beispiel-Usage**:
```bash
# Automatische Aktivierung bei Framework-Arbeit
/analyze --framework-compliance
# Manuelle Aktivierung
/implement --persona-framework-core --value-object UserProfile
# Kombination mit Standard-Personas
/improve --persona-value-object-architect --persona-refactorer
```

576
docs/claude/guidelines.md Normal file
View File

@@ -0,0 +1,576 @@
# Development Guidelines
Entwicklungsrichtlinien für das Custom PHP Framework.
## Code Style Principles
### Fundamental Code Standards
- **PSR-12 Coding Standards**: Befolge PSR-12 für einheitliche Code-Formatierung
- **PHP-CS-Fixer**: Automatische Code-Formatierung verwenden
- **Strict Types**: `declare(strict_types=1)` in allen PHP-Dateien
### Framework-Specific Principles
**No Inheritance Principle**:
```php
// ❌ Avoid extends - problematisch für Wartbarkeit
class UserController extends BaseController
{
// Problematische Vererbung
}
// ✅ Use composition - flexibler und testbarer
final readonly class UserController
{
public function __construct(
private readonly AuthService $auth,
private readonly UserRepository $userRepository,
private readonly Logger $logger
) {}
}
```
**Immutable by Design**:
```php
// ✅ Unveränderliche Objekte bevorzugen
final readonly class User
{
public function __construct(
public string $id,
public Email $email,
public string $name
) {}
// Neue Instanz für Änderungen
public function changeName(string $newName): self
{
return new self($this->id, $this->email, $newName);
}
}
```
**Readonly Everywhere**:
```php
// ✅ Classes und Properties readonly wo möglich
final readonly class ProductService
{
public function __construct(
private readonly ProductRepository $repository,
private readonly PriceCalculator $calculator
) {}
}
```
**Final by Default**:
```php
// ✅ Klassen sind final außer wenn explizit für Erweiterung designt
final readonly class OrderProcessor
{
// Implementation
}
// Nur wenn bewusst erweiterbar
readonly class BaseValidator
{
// Designed for extension
}
```
**Property Hooks Usage**:
```php
// ❌ Property Hooks in readonly Klassen - TECHNISCH NICHT MÖGLICH
final readonly class User
{
public string $fullName {
get => $this->firstName . ' ' . $this->lastName; // PHP Fehler!
}
}
// ✅ Normale Methoden in readonly Klassen verwenden
final readonly class User
{
public function getFullName(): string
{
return $this->firstName . ' ' . $this->lastName;
}
}
// ✅ Property Hooks nur in mutable Klassen verwenden
final class ConfigManager
{
private array $cache = [];
public string $apiKey {
set (string $value) {
if (empty($value)) {
throw new InvalidArgumentException('API key cannot be empty');
}
$this->apiKey = $value;
$this->cache = []; // Clear cache on change
}
}
public array $settings {
get => $this->cache ?: $this->cache = $this->loadSettings();
}
}
// ✅ private(set) für kontrollierte Mutation
final class EventStore
{
public private(set) array $events = [];
public function addEvent(DomainEvent $event): void
{
$this->events[] = $event;
}
}
```
**Property Hooks Richtlinien**:
- **TECHNISCH NICHT MÖGLICH** in `readonly` Klassen - PHP verbietet Property Hooks in readonly Klassen
- **Nur in mutable Klassen** verwenden
- **Alternative**: Normale Methoden in `readonly` Klassen für computed values
- **Use Cases**: Validation beim Setzen, Lazy Loading, Cache Invalidation
- **private(set)** für kontrollierte Array-Mutation in mutable Klassen
## Value Objects over Primitives
**Verwende Value Objects statt Arrays oder Primitives**:
```php
// ❌ Primitive Obsession vermeiden
function createUser(string $email, array $preferences): array
{
// Problematisch: keine Typsicherheit, versteckte Struktur
}
// ✅ Value Objects für Domain-Konzepte
function createUser(Email $email, UserPreferences $preferences): User
{
// Typsicher, selbstdokumentierend, validiert
}
```
**Domain Modeling mit Value Objects**:
```php
final readonly class Price
{
public function __construct(
public int $cents,
public Currency $currency
) {
if ($cents < 0) {
throw new \InvalidArgumentException('Preis kann nicht negativ sein');
}
}
public function toEuros(): float
{
return $this->cents / 100.0;
}
public function add(self $other): self
{
if (!$this->currency->equals($other->currency)) {
throw new \InvalidArgumentException('Currencies must match');
}
return new self($this->cents + $other->cents, $this->currency);
}
}
```
## Testing Standards
### Test Organization
**Mixed Testing Approach**:
- **Pest Framework**: Bevorzugt für neue Tests (moderne Syntax)
- **PHPUnit**: Traditionelle Tests beibehalten
- **Test Structure**: Tests spiegeln Source-Verzeichnisstruktur wider
```php
// ✅ Pest Test Beispiel
it('can calculate order total with tax', function () {
$order = new Order([
new OrderItem(new Price(1000, Currency::EUR), quantity: 2),
new OrderItem(new Price(500, Currency::EUR), quantity: 1)
]);
$calculator = new OrderCalculator(new TaxRate(0.19));
$total = $calculator->calculateTotal($order);
expect($total->cents)->toBe(2975); // 25€ + 19% tax
});
```
### Test Categories
- **Unit Tests**: Domain Logic, Value Objects, Services
- **Integration Tests**: Web Controller, Database Operations
- **Feature Tests**: End-to-End User Workflows
- **Performance Tests**: Critical Path Performance
## Security Guidelines
### Authentication & Authorization
**IP-based Authentication** für Admin Routes:
```php
#[Route(path: '/admin/dashboard', method: Method::GET)]
#[Auth(strategy: 'ip', allowedIps: ['127.0.0.1', '::1'])]
public function dashboard(HttpRequest $request): ViewResult
{
// Nur von erlaubten IP-Adressen erreichbar
}
```
**Route Protection**:
```php
#[Route(path: '/api/users', method: Method::POST)]
#[Auth(strategy: 'session', roles: ['admin'])]
public function createUser(CreateUserRequest $request): JsonResult
{
// Authentifizierung und Autorisierung erforderlich
}
```
### Input Validation
**Request Objects** für Validation:
```php
final readonly class CreateUserRequest implements ControllerRequest
{
public function __construct(
public Email $email,
public string $name,
public ?string $company = null
) {}
public static function fromHttpRequest(HttpRequest $request): self
{
$data = $request->parsedBody->toArray();
return new self(
email: new Email($data['email'] ?? ''),
name: trim($data['name'] ?? ''),
company: !empty($data['company']) ? trim($data['company']) : null
);
}
}
```
### Server Data Access
**Verwende Request::server statt Superglobals**:
```php
// ❌ Keine Superglobals verwenden
public function handleRequest(): JsonResult
{
$userAgent = $_SERVER['HTTP_USER_AGENT']; // Schlecht
$clientIp = $_SERVER['REMOTE_ADDR']; // Schlecht
}
// ✅ Request::server verwenden
public function handleRequest(HttpRequest $request): JsonResult
{
$userAgent = $request->server->getUserAgent();
$clientIp = $request->server->getClientIp();
$referer = $request->server->getSafeRefererUrl('/dashboard');
return new JsonResult([
'user_agent' => $userAgent->toString(),
'client_ip' => (string) $clientIp,
'safe_referer' => $referer
]);
}
### OWASP Security Events
**Security Event Logging**:
```php
// Automatisches Security Event Logging
final readonly class AuthenticationGuard
{
public function authenticate(LoginAttempt $attempt): AuthResult
{
if ($attempt->isRateLimited()) {
$this->eventLogger->logSecurityEvent(
new AuthenticationFailedEvent(
reason: 'Rate limit exceeded',
ipAddress: $attempt->ipAddress,
userAgent: $attempt->userAgent
)
);
throw new AuthenticationException('Too many attempts');
}
// Authentication logic
}
}
```
## Performance Guidelines
### Database Optimization
**EntityManager Usage**:
```php
// ✅ Bulk Operations verwenden
public function updateMultipleUsers(array $userUpdates): void
{
$this->entityManager->beginTransaction();
try {
foreach ($userUpdates as $update) {
$user = $this->entityManager->find(User::class, $update->userId);
$user->updateProfile($update->profileData);
// Keine sofortige Persistierung
}
$this->entityManager->flush(); // Bulk flush
$this->entityManager->commit();
} catch (\Exception $e) {
$this->entityManager->rollback();
throw $e;
}
}
```
**N+1 Query Prevention**:
```php
// ✅ Eager Loading verwenden
$users = $this->userRepository->findWithProfiles($userIds);
// Statt lazy loading in Schleife
// foreach ($users as $user) {
// $profile = $user->getProfile(); // N+1 Problem
// }
```
### Caching Strategy
**Framework Cache Interface mit Value Objects**:
```php
use App\Framework\Cache\Cache;
use App\Framework\Cache\CacheKey;
use App\Framework\Cache\CacheItem;
use App\Framework\Core\ValueObjects\Duration;
final readonly class UserService
{
public function __construct(
private readonly Cache $cache, // SmartCache ist Standard-Implementation
private readonly UserRepository $repository
) {}
public function getUser(string $userId): User
{
$cacheKey = CacheKey::fromString("user_{$userId}");
$ttl = Duration::fromHours(1);
// Remember Pattern mit Value Objects
$cacheItem = $this->cache->remember(
key: $cacheKey,
callback: fn() => $this->repository->find($userId),
ttl: $ttl
);
return $cacheItem->value;
}
public function cacheMultipleUsers(array $users): bool
{
$cacheItems = [];
foreach ($users as $user) {
$cacheItems[] = CacheItem::forSetting(
key: CacheKey::fromString("user_{$user->id}"),
value: $user,
ttl: Duration::fromHours(1)
);
}
// Batch-Operation mit SmartCache
return $this->cache->set(...$cacheItems);
}
}
```
**Advanced Cache Patterns**:
```php
// Cache mit Tags für gruppierte Invalidierung
$userKey = CacheKey::fromString("user_{$userId}");
$teamTag = CacheTag::fromString("team_{$teamId}");
$cacheItem = CacheItem::forSetting(
key: $userKey,
value: $user,
ttl: Duration::fromHours(2),
tags: [$teamTag]
);
$this->cache->set($cacheItem);
// Alle Team-bezogenen Caches invalidieren
$this->cache->forget($teamTag);
## Configuration Management
### Typed Configuration mit Environment Klasse
**Framework Environment Klasse verwenden**:
```php
final readonly class DatabaseConfig
{
public function __construct(
public string $host,
public int $port,
public string $database,
public string $username,
public string $password,
public string $driver = 'mysql'
) {}
public static function fromEnvironment(Environment $env): self
{
return new self(
host: $env->get(EnvKey::DB_HOST, 'localhost'),
port: $env->getInt(EnvKey::DB_PORT, 3306),
database: $env->require(EnvKey::DB_NAME),
username: $env->require(EnvKey::DB_USER),
password: $env->require(EnvKey::DB_PASS),
driver: $env->get(EnvKey::DB_DRIVER, 'mysql')
);
}
}
```
**EnvKey Enum für Type Safety**:
```php
// Environment Keys als Enum definieren
enum EnvKey: string
{
case DB_HOST = 'DB_HOST';
case DB_PORT = 'DB_PORT';
case DB_NAME = 'DB_NAME';
case DB_USER = 'DB_USER';
case DB_PASS = 'DB_PASS';
case DB_DRIVER = 'DB_DRIVER';
case APP_ENV = 'APP_ENV';
}
```
**Configuration Initializer Pattern**:
```php
final readonly class DatabaseConfigInitializer implements Initializer
{
public function __construct(
private readonly Environment $environment
) {}
public function initialize(Container $container): void
{
$config = DatabaseConfig::fromEnvironment($this->environment);
$container->singleton(DatabaseConfig::class, $config);
}
}
```
## Documentation Standards
### Code Documentation
**Self-Documenting Code bevorzugen**:
```php
// ✅ Code, der sich selbst erklärt
final readonly class OrderTotalCalculator
{
public function calculateTotalWithTax(
Order $order,
TaxRate $taxRate
): Money {
$subtotal = $this->calculateSubtotal($order);
$taxAmount = $subtotal->multiply($taxRate->asDecimal());
return $subtotal->add($taxAmount);
}
}
```
**PHPDoc nur wenn notwendig**:
```php
/**
* Berechnet Gesamtsumme nur für komplexe Business Logic
*
* @param Order $order - Customer order with line items
* @param TaxRate $taxRate - Applicable tax rate (0.0-1.0)
* @throws InvalidOrderException wenn Order leer ist
*/
public function calculateComplexTotal(Order $order, TaxRate $taxRate): Money
```
## Dependency Injection Best Practices
### Constructor Injection
**Explizite Dependencies**:
```php
// ✅ Alle Dependencies im Constructor
final readonly class OrderProcessor
{
public function __construct(
private readonly PaymentGateway $paymentGateway,
private readonly InventoryService $inventory,
private readonly EmailService $emailService,
private readonly Logger $logger
) {}
}
```
**Service Locator Anti-Pattern vermeiden**:
```php
// ❌ Service Locator Pattern
public function processOrder(Order $order): void
{
$gateway = ServiceLocator::get(PaymentGateway::class); // Schlecht
}
// ✅ Dependency Injection
public function processOrder(Order $order): void
{
$this->paymentGateway->charge($order->getTotal()); // Gut
}
```
## Framework Integration Patterns
### Environment-Aware Services
**Environment in Service Initialization**:
```php
final readonly class EmailServiceInitializer implements Initializer
{
public function __construct(
private readonly Environment $environment
) {}
public function initialize(Container $container): void
{
$service = match ($this->environment->get(EnvKey::APP_ENV)) {
'production' => new SmtpEmailService(
host: $this->environment->require(EnvKey::SMTP_HOST),
username: $this->environment->require(EnvKey::SMTP_USER),
password: $this->environment->require(EnvKey::SMTP_PASS)
),
'development' => new LogEmailService(),
default => new NullEmailService()
};
$container->singleton(EmailService::class, $service);
}
}
```

View File

@@ -0,0 +1,74 @@
# MCP Integration
**Model Context Protocol (MCP) Server Integration** für das Custom PHP Framework.
## Server Status
**✅ FULLY FUNCTIONAL**
- Server getestet und funktionsfähig mit JSON-RPC Protokoll
- Tools und Ressourcen bereit für AI-Integration
- Automatische Erkennung von Framework-Komponenten
- Sichere, sandbox-basierte Dateisystem-Zugriffe
## Quick Access Commands
```bash
# MCP Server starten
docker exec -i php php console.php mcp:server
# MCP Server testen
echo '{"jsonrpc": "2.0", "method": "initialize", "params": {}}' | docker exec -i php php console.php mcp:server
```
## Verfügbare MCP Tools
| Tool | Beschreibung | Verwendung |
|------|--------------|------------|
| `analyze_routes` | Alle registrierten Routen abrufen | Framework-Routing-Analyse |
| `analyze_container_bindings` | DI Container Bindings analysieren | Dependency Injection Debugging |
| `discover_attributes` | Attribute nach Typ entdecken | Framework-Pattern-Erkennung |
| `framework_health_check` | Health Check der Framework-Komponenten | System-Status-Überprüfung |
| `list_framework_modules` | Alle Framework-Module auflisten | Architektur-Übersicht |
| `list_directory` | Verzeichnisinhalte auflisten (projekt-beschränkt) | Dateisystem-Navigation |
| `read_file` | Dateiinhalte mit Zeilenlimits lesen | Code-Analyse |
| `find_files` | Dateien nach Pattern finden | Pattern-basierte Suche |
## MCP Resources
- `framework://config`: Framework-Konfiguration und Umgebung
## Claude Desktop Konfiguration
```json
{
"mcpServers": {
"custom-php-framework": {
"command": "docker",
"args": ["exec", "-i", "php", "php", "console.php", "mcp:server"],
"cwd": "/home/michael/dev/michaelschiemer"
}
}
}
```
## Framework-Analyse-Capabilities
- **Route Discovery**: Automatische Erkennung aller registrierten Routen
- **Container Binding Inspection**: Analyse der Dependency Injection Bindings
- **Modul- und Komponenten-Discovery**: Erkennung aller Framework-Module
- **Health Monitoring**: Überwachung des Framework-Status
- **File System Operations**: Projekt-beschränkte Dateisystem-Operationen
## Best Practices für AI-Interaktion
1. **MCP Tools verwenden**: Nutze MCP Tools für Framework-Analyse anstatt manueller Datei-Lesung
2. **Attribute Discovery nutzen**: Verwende Attribute-Discovery zum Verstehen der Framework-Patterns
3. **Health Checks**: Führe Framework Health Checks vor Änderungen durch
4. **Projekt-Scope beachten**: Respektiere projekt-beschränkte Dateizugriff-Limitierungen
## Sicherheitsfeatures
- **Sandboxed File Access**: Alle Dateizugriffe sind auf das Projekt beschränkt
- **Safe Operations**: Nur lesende Operationen für Framework-Analyse
- **Validation**: Eingabe-Validierung für alle MCP-Tool-Parameter
- **Error Handling**: Robuste Fehlerbehandlung mit aussagekräftigen Meldungen

View File

@@ -0,0 +1,31 @@
# Performance Monitoring
This guide covers performance monitoring and optimization features.
## Performance Collector
TODO: Document PerformanceCollector usage
## Metrics System
TODO: Document metrics collection and reporting
## Circuit Breaker Pattern
TODO: Document circuit breaker implementation
## Cache Performance
TODO: Document cache metrics and optimization
## Database Performance
TODO: Document query analysis and optimization
## Performance Testing
TODO: Document performance testing strategies
## Optimization Techniques
TODO: List performance optimization techniques

View File

@@ -0,0 +1,31 @@
# Queue System
This guide covers the queue system and background job processing.
## Queue Interface
TODO: Document Queue interface and implementations
## Background Jobs
TODO: Document background job creation and processing
## Queue Drivers
TODO: Document available queue drivers (Redis, File, etc.)
## Retry Mechanisms
TODO: Document retry strategies and configuration
## Failed Jobs
TODO: Document failed job handling
## Queue Monitoring
TODO: Document queue monitoring and metrics
## Best Practices
TODO: List queue system best practices

View File

@@ -0,0 +1,31 @@
# Security Patterns
This guide covers security best practices and patterns used in the framework.
## OWASP Event Integration
TODO: Document OWASP security event handling
## Web Application Firewall (WAF)
TODO: Document WAF usage and configuration
## Authentication & Authorization
TODO: Document auth patterns and IP-based authentication
## CSRF Protection
TODO: Document CSRF token handling
## Security Headers
TODO: Document security headers configuration
## Input Validation
TODO: Document input validation and sanitization
## Security Best Practices
TODO: List general security guidelines

View File

@@ -0,0 +1,31 @@
# Troubleshooting
This guide helps diagnose and fix common issues.
## Common Errors
TODO: Document frequent errors and solutions
## Container/DI Issues
TODO: Document dependency injection problems
## Routing Problems
TODO: Document route conflicts and resolution
## Performance Issues
TODO: Document performance problem diagnosis
## Database Connection Issues
TODO: Document database troubleshooting
## Cache Problems
TODO: Document cache-related issues
## Debug Tools
TODO: Document available debugging tools and techniques