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:
14
backups/docs-backup-20250731125004/framework/ANALYTICS.md
Normal file
14
backups/docs-backup-20250731125004/framework/ANALYTICS.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Analytics-Framework
|
||||
|
||||
> **Dokumentationshinweis:** Die vollständige Dokumentation für das Analytics-Framework finden Sie im Ordner [/docs/framework/analytics](/docs/framework/analytics/).
|
||||
|
||||
## Schnellzugriff
|
||||
|
||||
- [Übersicht und Einstieg](/docs/framework/analytics/index.md)
|
||||
- [Detaillierte Architektur](/docs/framework/analytics/architecture.md)
|
||||
- [Anwendungsbeispiele](/docs/framework/analytics/usage.md)
|
||||
- [Migrationsleitfaden](/docs/framework/analytics/migration.md)
|
||||
|
||||
## Implementierungsdetails
|
||||
|
||||
Die Code-Dokumentation befindet sich in der [README-Datei des Frameworks](/Framework/Analytics1/README.md).
|
||||
@@ -0,0 +1,200 @@
|
||||
# Erweiterungsmuster im Framework
|
||||
|
||||
## Übersicht
|
||||
|
||||
Dieses Dokument beschreibt die verschiedenen Muster und Techniken, um das Framework zu erweitern oder anzupassen, ohne den Kern-Code zu verändern.
|
||||
|
||||
## Event-basierte Erweiterungen
|
||||
|
||||
### Event-Listener
|
||||
|
||||
Die primäre Methode zur Erweiterung des Frameworks ist das Lauschen auf System-Events:
|
||||
|
||||
```php
|
||||
// Event-Listener registrieren
|
||||
public function __construct(private readonly EventDispatcher $eventDispatcher)
|
||||
{
|
||||
$this->eventDispatcher->addHandler(
|
||||
'App\Framework\Core\Events\ApplicationBooted',
|
||||
[$this, 'onApplicationBooted']
|
||||
);
|
||||
}
|
||||
|
||||
// Event-Handler-Methode
|
||||
public function onApplicationBooted(ApplicationBooted $event): void
|
||||
{
|
||||
// Erweiterungslogik implementieren
|
||||
}
|
||||
```
|
||||
|
||||
### Eigene Events
|
||||
|
||||
Benutzerdefinierte Events erstellen:
|
||||
|
||||
```php
|
||||
final readonly class UserRegistered
|
||||
{
|
||||
public function __construct(
|
||||
public string $userId,
|
||||
public string $email,
|
||||
public \DateTimeImmutable $timestamp
|
||||
) {}
|
||||
}
|
||||
|
||||
// Event auslösen
|
||||
$this->eventDispatcher->dispatch(new UserRegistered(
|
||||
$user->getId(),
|
||||
$user->getEmail(),
|
||||
new \DateTimeImmutable()
|
||||
));
|
||||
```
|
||||
|
||||
## Middleware
|
||||
|
||||
HTTP-Anfragen können durch Middleware-Klassen erweitert werden:
|
||||
|
||||
```php
|
||||
final readonly class CustomMiddleware implements Middleware
|
||||
{
|
||||
public function process(Request $request, callable $next): Response
|
||||
{
|
||||
// Vor der Anfrageverarbeitung
|
||||
$modifiedRequest = $this->modifyRequest($request);
|
||||
|
||||
// Anfrage weiterleiten
|
||||
$response = $next($modifiedRequest);
|
||||
|
||||
// Nach der Anfrageverarbeitung
|
||||
return $this->modifyResponse($response);
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware registrieren
|
||||
$app->addMiddleware(CustomMiddleware::class);
|
||||
```
|
||||
|
||||
## Service-Erweiterungen
|
||||
|
||||
### Service-Ersetzen
|
||||
|
||||
Standardimplementierungen durch eigene ersetzen:
|
||||
|
||||
```php
|
||||
#[Initializer]
|
||||
final readonly class CustomStorageInitializer
|
||||
{
|
||||
public function __invoke(Container $container): StorageInterface
|
||||
{
|
||||
return new CustomStorage();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Service-Decorator
|
||||
|
||||
Bestehende Services erweitern ohne Änderung der Original-Implementierung:
|
||||
|
||||
```php
|
||||
#[Initializer]
|
||||
final readonly class LoggingAnalyticsInitializer
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Configuration $config,
|
||||
private readonly LoggerInterface $logger
|
||||
) {}
|
||||
|
||||
public function __invoke(Container $container): Analytics
|
||||
{
|
||||
// Original-Analytics-Service erstellen
|
||||
$originalAnalytics = new Analytics(
|
||||
new AnalyticsManager($this->config->get('analytics'), new FileStorage($path)),
|
||||
$container->get(EventDispatcher::class)
|
||||
);
|
||||
|
||||
// Mit Logging-Decorator umhüllen
|
||||
return new LoggingAnalyticsDecorator($originalAnalytics, $this->logger);
|
||||
}
|
||||
}
|
||||
|
||||
// Decorator-Implementierung
|
||||
final readonly class LoggingAnalyticsDecorator implements AnalyticsInterface
|
||||
{
|
||||
public function __construct(
|
||||
private Analytics $analytics,
|
||||
private LoggerInterface $logger
|
||||
) {}
|
||||
|
||||
public function track(string $event, array $properties = [], ?string $userId = null): void
|
||||
{
|
||||
$this->logger->debug("Tracking event: {$event}", [
|
||||
'properties' => $properties,
|
||||
'user_id' => $userId
|
||||
]);
|
||||
|
||||
$this->analytics->track($event, $properties, $userId);
|
||||
}
|
||||
|
||||
// Andere Methoden implementieren
|
||||
}
|
||||
```
|
||||
|
||||
## Plugin-System
|
||||
|
||||
### Plugin-Interface
|
||||
|
||||
```php
|
||||
interface PluginInterface
|
||||
{
|
||||
public function register(Application $app): void;
|
||||
public function boot(Application $app): void;
|
||||
}
|
||||
|
||||
// Plugin-Implementierung
|
||||
final readonly class CustomPlugin implements PluginInterface
|
||||
{
|
||||
public function register(Application $app): void
|
||||
{
|
||||
// Services registrieren
|
||||
}
|
||||
|
||||
public function boot(Application $app): void
|
||||
{
|
||||
// Nach Initialisierung der Anwendung
|
||||
}
|
||||
}
|
||||
|
||||
// Plugin registrieren
|
||||
$app->registerPlugin(new CustomPlugin());
|
||||
```
|
||||
|
||||
## Konfigurationserweiterungen
|
||||
|
||||
### Konfigurationsquellen
|
||||
|
||||
Benutzerdefinierte Konfigurationsquellen implementieren:
|
||||
|
||||
```php
|
||||
final readonly class EnvironmentConfigSource implements ConfigSourceInterface
|
||||
{
|
||||
public function load(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$envKey = strtoupper(str_replace('.', '_', $key));
|
||||
return $_ENV[$envKey] ?? $default;
|
||||
}
|
||||
}
|
||||
|
||||
// Konfigurationsquelle registrieren
|
||||
$config->addSource(new EnvironmentConfigSource());
|
||||
```
|
||||
|
||||
## Zusammenfassung
|
||||
|
||||
Die bevorzugten Erweiterungsmuster sind:
|
||||
|
||||
1. **Event-Listener** für reaktive Erweiterungen
|
||||
2. **Middleware** für HTTP-Anfrageverarbeitung
|
||||
3. **Service-Initializer** zum Ersetzen oder Dekorieren von Services
|
||||
4. **Plugins** für umfassendere Funktionalitätserweiterungen
|
||||
5. **Konfigurationsquellen** für benutzerdefinierte Konfigurationen
|
||||
|
||||
Diese Muster ermöglichen es, das Framework zu erweitern, ohne den Kern zu modifizieren, was zu einer besseren Wartbarkeit und einfacheren Updates führt.
|
||||
@@ -0,0 +1,73 @@
|
||||
# Framework-Modul Checkliste
|
||||
|
||||
## Übersicht
|
||||
|
||||
Diese Checkliste dient als Leitfaden für die Erstellung neuer Module im Framework. Sie hilft sicherzustellen, dass alle Module den Projektstandards entsprechen und konsistent implementiert werden.
|
||||
|
||||
## Strukturelle Anforderungen
|
||||
|
||||
- [ ] Modul in eigenem Verzeichnis unter `/src/Framework/`
|
||||
- [ ] Konsistente Namensgebung im PascalCase (z.B. `CacheManager` statt `Cache_manager`)
|
||||
- [ ] README.md mit Modul-Dokumentation
|
||||
- [ ] Interface(s) für öffentliche API
|
||||
- [ ] Implementierungsklassen als `final readonly`
|
||||
- [ ] Initializer-Klasse mit `#[Initializer]`-Attribut
|
||||
|
||||
## Abhängigkeiten
|
||||
|
||||
- [ ] Minimale externe Abhängigkeiten (idealerweise keine)
|
||||
- [ ] Klar definierte Abhängigkeiten zu anderen Framework-Modulen
|
||||
- [ ] Keine zirkulären Abhängigkeiten
|
||||
- [ ] Verwendung des DI-Containers für Abhängigkeiten
|
||||
|
||||
## Konfiguration
|
||||
|
||||
- [ ] Konfigurationsdatei unter `/src/Config/{modul-name}.php`
|
||||
- [ ] Standardkonfiguration in der Initializer-Klasse
|
||||
- [ ] Dokumentierte Konfigurationsoptionen
|
||||
|
||||
## Code-Qualität
|
||||
|
||||
- [ ] Vollständige Typisierung (Parameter, Rückgabewerte, Properties)
|
||||
- [ ] PHPDoc für öffentliche Methoden und Klassen
|
||||
- [ ] Keine abstrakten Klassen oder Vererbung (außer Interfaces)
|
||||
- [ ] Immutable Objekte wo möglich
|
||||
- [ ] Spezifische Exceptions für Fehlerbehandlung
|
||||
|
||||
## Tests
|
||||
|
||||
- [ ] Unit-Tests mit Pest für alle öffentlichen Methoden
|
||||
- [ ] Integrationstests für Modul-Interaktionen
|
||||
- [ ] Testabdeckung für Fehlerfälle
|
||||
|
||||
## Integration
|
||||
|
||||
- [ ] Event-Listener für relevante System-Events
|
||||
- [ ] Erweiterungspunkte für andere Module
|
||||
- [ ] Keine direkten Abhängigkeiten zu Domain-Klassen
|
||||
|
||||
## Dokumentation
|
||||
|
||||
- [ ] Beispiele für Verwendung
|
||||
- [ ] Architektur-Beschreibung
|
||||
- [ ] API-Dokumentation
|
||||
- [ ] Konfigurationsreferenz
|
||||
|
||||
## Performance
|
||||
|
||||
- [ ] Lazy-Loading für ressourcenintensive Operationen
|
||||
- [ ] Caching-Strategie (falls relevant)
|
||||
- [ ] Performancekritische Teile identifiziert und optimiert
|
||||
|
||||
## Sicherheit
|
||||
|
||||
- [ ] Validierung aller externen Eingaben
|
||||
- [ ] Keine sensiblen Daten in Logs
|
||||
- [ ] Schutz vor bekannten Sicherheitslücken
|
||||
|
||||
## Wartbarkeit
|
||||
|
||||
- [ ] Kleine, fokussierte Klassen
|
||||
- [ ] Klare Trennung von Verantwortlichkeiten
|
||||
- [ ] Konsistente Fehlerbehandlung
|
||||
- [ ] Logging an strategischen Stellen
|
||||
158
backups/docs-backup-20250731125004/framework/analytics/README.md
Normal file
158
backups/docs-backup-20250731125004/framework/analytics/README.md
Normal file
@@ -0,0 +1,158 @@
|
||||
# Analytics-Modul Dokumentation
|
||||
|
||||
## Übersicht
|
||||
|
||||
Das Analytics-Modul ist ein internes Tracking- und Analysesystem, das ohne externe Abhängigkeiten Benutzeraktivitäten, Systemereignisse und Leistungsdaten erfasst und analysiert.
|
||||
|
||||
## Kernkomponenten
|
||||
|
||||
### Analytics (Analytics.php)
|
||||
|
||||
Die Hauptklasse, die als zentraler Einstiegspunkt für das Tracking von Events dient.
|
||||
|
||||
**Hauptfunktionen:**
|
||||
- `track()`: Zeichnet ein generisches Event auf
|
||||
- `page()`: Spezifisch für Seitenaufrufe
|
||||
- `user()`: Verfolgt Benutzeridentifikation
|
||||
- `performance()`: Erfasst Leistungsmetriken
|
||||
- `error()`: Protokolliert Fehler und Ausnahmen
|
||||
|
||||
### AnalyticsManager (AnalyticsManager.php)
|
||||
|
||||
Verwaltet die Verarbeitung und Speicherung von Events.
|
||||
|
||||
**Hauptfunktionen:**
|
||||
- `track()`: Verarbeitet Events und wendet Middleware an
|
||||
- `addMiddleware()`: Fügt Verarbeitungsfunktionen hinzu
|
||||
- `flush()`: Schreibt gepufferte Events in den Speicher
|
||||
|
||||
### StorageInterface und FileStorage
|
||||
|
||||
Das Interface definiert die Speichermethoden, FileStorage implementiert die Speicherung in Dateien.
|
||||
|
||||
**Hauptoperationen:**
|
||||
- `store()`: Speichert Events
|
||||
- `retrieve()`: Ruft Events mit Filtern ab
|
||||
- `clear()`: Löscht alle gespeicherten Daten
|
||||
|
||||
### AnalyticsInitializer (AnalyticsInitializer.php)
|
||||
|
||||
Konfiguriert und initialisiert den Analytics-Service beim Anwendungsstart.
|
||||
|
||||
**Konfigurationsoptionen:**
|
||||
- Aktivierung/Deaktivierung
|
||||
- Auto-Flush und Batch-Größe
|
||||
- Storage-Typ und Pfad
|
||||
|
||||
### AnalyticsMiddleware (AnalyticsMiddleware.php)
|
||||
|
||||
HTTP-Middleware zum automatischen Tracking von Requests und Responses.
|
||||
|
||||
### AnalyticsDashboard (AnalyticsDashboard.php)
|
||||
|
||||
Stellt Methoden für Datenanalyse und -aggregation bereit:
|
||||
- `getEventStats()`: Ereignisstatistiken
|
||||
- `getTopPages()`: Meistbesuchte Seiten
|
||||
- `getUserStats()`: Benutzerstatistiken
|
||||
- `getErrorStats()`: Fehlerstatistiken
|
||||
- `getPerformanceStats()`: Leistungsmetriken
|
||||
|
||||
### Events
|
||||
|
||||
Vordefinierte Event-Typen:
|
||||
- `AnalyticsEvent`: Basis-Event-Klasse
|
||||
- `PageViewEvent`: Speziell für Seitenaufrufe
|
||||
|
||||
### Controllers
|
||||
|
||||
`AdminAnalyticsController`: Stellt das Admin-Dashboard bereit mit:
|
||||
- Übersichtsseite
|
||||
- Seitenstatistiken
|
||||
- Fehlerstatistiken
|
||||
- Leistungsstatistiken
|
||||
|
||||
### Console
|
||||
|
||||
`AnalyticsClearCommand`: Konsolenbefehl zum Löschen von Analytics-Daten.
|
||||
|
||||
## Konfiguration
|
||||
|
||||
Die Konfiguration erfolgt in `src/Config/analytics.php` mit folgenden Optionen:
|
||||
|
||||
```php
|
||||
return [
|
||||
'enabled' => true, // Aktiviert/deaktiviert das Tracking
|
||||
'auto_flush' => true, // Automatisches Speichern nach Batch-Größe
|
||||
'batch_size' => 50, // Anzahl Events pro Batch
|
||||
'storage' => 'file', // Storage-Backend
|
||||
'storage_path' => '...', // Speicherpfad
|
||||
'anonymize_ip' => true, // IP-Anonymisierung
|
||||
'track_events' => [...] // Zu trackende Events
|
||||
];
|
||||
```
|
||||
|
||||
## Verwendung
|
||||
|
||||
### Basis-Tracking
|
||||
|
||||
```php
|
||||
// Event tracken
|
||||
$analytics->track('button_click', ['button' => 'signup']);
|
||||
|
||||
// Seitenaufruf tracken
|
||||
$analytics->page('/dashboard', ['section' => 'analytics']);
|
||||
|
||||
// Benutzer identifizieren
|
||||
$analytics->user('user123', ['plan' => 'premium']);
|
||||
```
|
||||
|
||||
### Middleware einrichten
|
||||
|
||||
```php
|
||||
$this->addMiddleware(App\Framework\Analytics\AnalyticsMiddleware::class);
|
||||
```
|
||||
|
||||
### Eigene Middleware hinzufügen
|
||||
|
||||
```php
|
||||
$analyticsManager->addMiddleware(function(array $event) {
|
||||
// Daten verarbeiten oder filtern
|
||||
return $event;
|
||||
});
|
||||
```
|
||||
|
||||
## Datenschutz
|
||||
|
||||
Das System bietet integrierte Funktionen zur Anonymisierung personenbezogener Daten:
|
||||
- IP-Adressen-Anonymisierung (letztes Oktett wird entfernt)
|
||||
- Konfigurierbare Filterung sensibler Daten durch Middleware
|
||||
|
||||
## Erweiterbarkeit
|
||||
|
||||
### Eigene Storage-Provider
|
||||
|
||||
Implementieren Sie das `StorageInterface` für benutzerdefinierte Speicherlösungen:
|
||||
|
||||
```php
|
||||
class CustomStorage implements StorageInterface
|
||||
{
|
||||
public function store(array $events): void { /* ... */ }
|
||||
public function retrieve(array $filters = []): array { /* ... */ }
|
||||
public function clear(): void { /* ... */ }
|
||||
}
|
||||
```
|
||||
|
||||
### Event-Typen erweitern
|
||||
|
||||
Erstellen Sie benutzerdefinierte Event-Klassen, die von `AnalyticsEvent` erben:
|
||||
|
||||
```php
|
||||
class CustomEvent extends AnalyticsEvent
|
||||
{
|
||||
public function __construct(string $customData, array $additionalProps = [])
|
||||
{
|
||||
parent::__construct('custom_event',
|
||||
array_merge(['custom_data' => $customData], $additionalProps));
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,102 @@
|
||||
# Analytics-Framework: Architektur
|
||||
|
||||
## Überblick
|
||||
|
||||
Das Analytics-Framework verwendet eine Schichtenarchitektur mit klaren Verantwortlichkeiten:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Öffentliche API │
|
||||
│ (Analytics) │
|
||||
└───────────────────────┬─────────────────────────────┘
|
||||
│
|
||||
┌───────────────────────▼─────────────────────────────┐
|
||||
│ Event-Verarbeitung │
|
||||
│ (AnalyticsManager) │
|
||||
└───────────────────────┬─────────────────────────────┘
|
||||
│
|
||||
┌──────────────┴──────────────┐
|
||||
│ │
|
||||
┌────────▼─────────┐ ┌─────────▼────────┐
|
||||
│ Middleware │ │ Storage-Layer │
|
||||
│ (Pipeline) │ │ (StorageInterface)│
|
||||
└──────────────────┘ └──────────────────┘
|
||||
```
|
||||
|
||||
## Komponenten im Detail
|
||||
|
||||
### Analytics (Frontend)
|
||||
|
||||
Bietet eine benutzerfreundliche API für Tracking-Operationen. Diese Klasse ist der primäre Einstiegspunkt für Anwendungscode und abstrahiert die Komplexität der Eventverarbeitung.
|
||||
|
||||
Verantwortlichkeiten:
|
||||
- Bereitstellung der öffentlichen API (`track`, `page`, `user`, `error`)
|
||||
- Integration mit dem Event-Dispatcher des Frameworks
|
||||
- Typ-Konvertierung zwischen benutzerdefinierten Ereignissen und dem internen Datenformat
|
||||
|
||||
### AnalyticsManager (Verarbeitung)
|
||||
|
||||
Der Manager ist das Herzstück des Systems und verantwortlich für:
|
||||
- Anwendung von Middleware-Transformationen auf Events
|
||||
- Eventpufferung für effiziente Speicherung
|
||||
- Verwaltung der Konfiguration
|
||||
- Steuerung des Storage-Layers
|
||||
|
||||
Der Manager implementiert einen Event-Buffer, der Daten sammelt und bei Erreichen einer konfigurierbaren Größe automatisch speichert.
|
||||
|
||||
### Middleware-System
|
||||
|
||||
Eine Kette von Verarbeitungsfunktionen, die auf jedes Event angewendet werden:
|
||||
- Datenfilterung und -transformation
|
||||
- Anonymisierung persönlicher Daten
|
||||
- Validierung und Anreicherung von Events
|
||||
|
||||
Jede Middleware kann Events modifizieren oder komplett verwerfen.
|
||||
|
||||
### Storage-Layer
|
||||
|
||||
Abstraktion für verschiedene Speichermethoden durch das `StorageInterface`:
|
||||
|
||||
```php
|
||||
interface StorageInterface
|
||||
{
|
||||
public function store(array $events): void;
|
||||
public function retrieve(array $filters = []): array;
|
||||
public function clear(): void;
|
||||
}
|
||||
```
|
||||
|
||||
Implementierungen:
|
||||
- `FileStorage`: Speichert Events in JSON-Dateien mit täglicher Rotation
|
||||
- Erweiterbar für andere Backends (Datenbank, Redis, etc.)
|
||||
|
||||
### HTTP-Integration
|
||||
|
||||
`AnalyticsMiddleware` integriert Analytics in den HTTP-Request-Lifecycle:
|
||||
- Tracking von eingehenden Requests
|
||||
- Erfassung von Antwortzeiten und Statuscodes
|
||||
- Fehlererfassung bei Exceptions
|
||||
|
||||
### Admin-Dashboard
|
||||
|
||||
`AnalyticsDashboard` und `AdminAnalyticsController` bieten:
|
||||
- Datenaggregation und -analyse
|
||||
- Visualisierung von Metriken
|
||||
- Filterung nach Zeiträumen
|
||||
- Verschiedene spezialisierte Ansichten (Seiten, Fehler, Performance)
|
||||
|
||||
## Datenfluss
|
||||
|
||||
1. Event wird durch `Analytics::track()` oder ähnliche Methoden erstellt
|
||||
2. `AnalyticsManager` wendet Middleware-Pipeline an
|
||||
3. Event wird zum Buffer hinzugefügt
|
||||
4. Bei Buffer-Füllung oder explizitem `flush()` werden Events an Storage übergeben
|
||||
5. Storage speichert Events im konfigurierten Backend
|
||||
6. `AnalyticsDashboard` ruft Daten bei Bedarf vom Storage ab und aggregiert sie
|
||||
|
||||
## Erweiterungspunkte
|
||||
|
||||
- **Storage-Provider**: Neue Implementierungen von `StorageInterface`
|
||||
- **Middleware**: Funktionen für Filterung/Transformation
|
||||
- **Event-Typen**: Spezialisierte Event-Klassen für typsicheres Tracking
|
||||
- **Dashboard-Views**: Zusätzliche Visualisierungen und Berichte
|
||||
114
backups/docs-backup-20250731125004/framework/analytics/index.md
Normal file
114
backups/docs-backup-20250731125004/framework/analytics/index.md
Normal file
@@ -0,0 +1,114 @@
|
||||
# Analytics-Framework
|
||||
|
||||
> **Dokumentationshinweis:** Diese Dokumentation ist vollständig aktualisiert und stellt die aktuelle Implementierung des Analytics-Frameworks korrekt dar.
|
||||
|
||||
## Übersicht
|
||||
|
||||
Das Analytics-Framework ist ein eigenständiges Tracking- und Analysesystem, das vollständig in die Anwendung integriert ist und ohne externe Dienste auskommt. Es ermöglicht die Erfassung, Speicherung und Analyse von:
|
||||
|
||||
- Benutzeraktivitäten (Seitenaufrufe, Interaktionen)
|
||||
- Systemereignissen (Anwendungsstart, Fehler)
|
||||
- Leistungsdaten (Speicherverbrauch, Ausführungszeit, Datenbankabfragen)
|
||||
|
||||
## Hauptkomponenten
|
||||
|
||||
### Analytics-Klasse
|
||||
|
||||
Die zentrale API für Tracking-Operationen:
|
||||
|
||||
```php
|
||||
// Klasse initialisieren
|
||||
$analytics = new Analytics($analyticsManager, $eventDispatcher);
|
||||
|
||||
// Event tracken
|
||||
$analytics->track('event_name', ['property' => 'value']);
|
||||
|
||||
// Seite tracken
|
||||
$analytics->page('/pfad/zur/seite', ['eigenschaft' => 'wert']);
|
||||
|
||||
// Benutzer identifizieren
|
||||
$analytics->user('user_id', ['eigenschaft' => 'wert']);
|
||||
|
||||
// Fehler tracken
|
||||
$analytics->error($exception);
|
||||
```
|
||||
|
||||
### AnalyticsManager
|
||||
|
||||
Verarbeitet und speichert Events:
|
||||
|
||||
- Wendet Middleware auf Events an
|
||||
- Puffert Events für effiziente Speicherung
|
||||
- Verwaltet die Konfiguration
|
||||
- Steuert die Speicherung in verschiedenen Backends
|
||||
|
||||
### Storage-System
|
||||
|
||||
Basierend auf dem `StorageInterface` mit verschiedenen Implementierungen:
|
||||
|
||||
- `FileStorage`: Speichert Events in Dateien
|
||||
- Erweiterbar für Datenbank, Redis oder andere Backends
|
||||
|
||||
### Middleware-System
|
||||
|
||||
```php
|
||||
$analyticsManager->addMiddleware(function(array $event) {
|
||||
// Event verarbeiten oder filtern
|
||||
return $event; // oder null um zu verwerfen
|
||||
});
|
||||
```
|
||||
|
||||
### HTTP-Middleware
|
||||
|
||||
Automatisches Tracking von HTTP-Requests und -Responses:
|
||||
|
||||
```php
|
||||
// In Bootstrap oder Application-Klasse
|
||||
$app->addMiddleware(AnalyticsMiddleware::class);
|
||||
```
|
||||
|
||||
### Dashboard und Berichterstattung
|
||||
|
||||
Das `AnalyticsDashboard` bietet Methoden zur Datenanalyse:
|
||||
|
||||
- `getEventStats()`: Statistiken zu Events
|
||||
- `getTopPages()`: Meistbesuchte Seiten
|
||||
- `getUserStats()`: Benutzerstatistiken
|
||||
- `getErrorStats()`: Fehlerstatistiken
|
||||
- `getPerformanceStats()`: Leistungsmetriken
|
||||
|
||||
Das Admin-Dashboard ist unter `/admin/analytics` verfügbar.
|
||||
|
||||
### Konsolen-Befehle
|
||||
|
||||
```bash
|
||||
# Analytics-Daten löschen
|
||||
php console analytics:clear [--force]
|
||||
```
|
||||
|
||||
## Integration
|
||||
|
||||
### Service-Container
|
||||
|
||||
Der Analytics-Service wird automatisch registriert und kann per Dependency Injection verwendet werden:
|
||||
|
||||
```php
|
||||
public function __construct(private readonly Analytics $analytics) {}
|
||||
```
|
||||
|
||||
### Event-Integration
|
||||
|
||||
Standardmäßig werden folgende Anwendungsereignisse getrackt:
|
||||
|
||||
- Anwendungsstart (`application_booted`)
|
||||
- Fehlerbehandlung (`error_occurred`)
|
||||
- Request-Verarbeitung (`request_started`, `request_completed`)
|
||||
|
||||
## Konfiguration
|
||||
|
||||
Detaillierte Konfigurationsoptionen finden Sie in der [Framework-README](/Framework/Analytics1/README.md).
|
||||
|
||||
## Weitere Informationen
|
||||
|
||||
- [Framework-Erweiterungsmuster](/docs/framework/ERWEITERUNGSPATTERN.md)
|
||||
- [Modul-Checkliste](/docs/framework/MODUL-CHECKLISTE.md)
|
||||
@@ -0,0 +1,160 @@
|
||||
# Analytics-Framework: Migrationsleitfaden
|
||||
|
||||
## Von Version 1.x zu 2.x
|
||||
|
||||
### Überblick der Änderungen
|
||||
|
||||
Die Version 2.x des Analytics-Frameworks führt mehrere wichtige Verbesserungen und Änderungen ein:
|
||||
|
||||
- **Typsicherheit**: Neue Event-Klassen statt Arrays
|
||||
- **Dependency Injection**: Verbesserte Integration mit dem Container
|
||||
- **Storage-Abstraktion**: Flexiblere Speichermethoden
|
||||
- **Fehlerbehandlung**: Robustere Exception-Handling
|
||||
- **Middleware-System**: Standardisierte Middleware-Pipeline
|
||||
|
||||
### Notwendige Migrationsschritte
|
||||
|
||||
#### 1. Konfiguration aktualisieren
|
||||
|
||||
**Alt (1.x):**
|
||||
```php
|
||||
return [
|
||||
'enabled' => true,
|
||||
'auto_flush' => true,
|
||||
'batch_size' => 50,
|
||||
'storage' => 'file',
|
||||
'storage_path' => '/pfad/zum/speicher',
|
||||
];
|
||||
```
|
||||
|
||||
**Neu (2.x):**
|
||||
```php
|
||||
return [
|
||||
'enabled' => true,
|
||||
'auto_flush' => true,
|
||||
'batch_size' => 50,
|
||||
'storage_driver' => 'file', // Umbenannt
|
||||
'storage_config' => [ // Neue Struktur
|
||||
'path' => '/pfad/zum/speicher',
|
||||
],
|
||||
'excluded_paths' => [], // Neue Option
|
||||
'excluded_user_agents' => [], // Neue Option
|
||||
'max_file_size' => 10 * 1024 * 1024, // Neue Option
|
||||
];
|
||||
```
|
||||
|
||||
#### 2. Event-Objekte (falls genutzt)
|
||||
|
||||
**Alt (1.x):**
|
||||
```php
|
||||
$analytics->track('custom_event', ['property' => 'value']);
|
||||
```
|
||||
|
||||
**Neu (2.x) - Option 1 (abwärtskompatibel):**
|
||||
```php
|
||||
// Weiterhin unterstützt
|
||||
$analytics->track('custom_event', ['property' => 'value']);
|
||||
```
|
||||
|
||||
**Neu (2.x) - Option 2 (typsicher):**
|
||||
```php
|
||||
use App\Framework\Analytics\Events\CustomEvent;
|
||||
|
||||
$event = new CustomEvent('wert', ['weitere' => 'daten']);
|
||||
$analytics->trackEvent($event);
|
||||
```
|
||||
|
||||
#### 3. Eigene Storage-Provider
|
||||
|
||||
**Alt (1.x):**
|
||||
```php
|
||||
class CustomStorage implements StorageInterface
|
||||
{
|
||||
public function store(array $events): void
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
|
||||
public function retrieve(array $filters = []): array
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Neu (2.x):**
|
||||
```php
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class CustomStorage implements StorageInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly array $config,
|
||||
private readonly LoggerInterface $logger
|
||||
) {}
|
||||
|
||||
public function store(array $events): void
|
||||
{
|
||||
try {
|
||||
// Implementation mit Fehlerbehandlung
|
||||
} catch (\Exception $e) {
|
||||
$this->logger->error('Storage error', ['exception' => $e]);
|
||||
throw new StorageException('Failed to store events', 0, $e);
|
||||
}
|
||||
}
|
||||
|
||||
// Andere Methoden analog
|
||||
}
|
||||
```
|
||||
|
||||
#### 4. Middleware anpassen
|
||||
|
||||
**Alt (1.x):**
|
||||
```php
|
||||
$analyticsManager->addMiddleware(function(array $event) {
|
||||
// Verarbeitung
|
||||
return $event;
|
||||
});
|
||||
```
|
||||
|
||||
**Neu (2.x) - Option 1 (abwärtskompatibel):**
|
||||
```php
|
||||
// Weiterhin unterstützt
|
||||
$analyticsManager->addMiddleware(function(array $event) {
|
||||
// Verarbeitung
|
||||
return $event;
|
||||
});
|
||||
```
|
||||
|
||||
**Neu (2.x) - Option 2 (typsicher):**
|
||||
```php
|
||||
use App\Framework\Analytics\Middleware\AnalyticsMiddleware;
|
||||
use App\Framework\Analytics\Events\AnalyticsEvent;
|
||||
|
||||
class CustomMiddleware implements AnalyticsMiddleware
|
||||
{
|
||||
public function process(AnalyticsEvent $event): ?AnalyticsEvent
|
||||
{
|
||||
// Verarbeitung
|
||||
return $event;
|
||||
}
|
||||
}
|
||||
|
||||
// Registrierung
|
||||
$analyticsManager->addMiddleware(new CustomMiddleware());
|
||||
```
|
||||
|
||||
### Automatisierte Tests
|
||||
|
||||
Führen Sie die folgenden Tests durch, um sicherzustellen, dass die Migration erfolgreich war:
|
||||
|
||||
```bash
|
||||
php console test:run --group=analytics
|
||||
```
|
||||
|
||||
Weitere Informationen zur Migration finden Sie in den Änderungsprotokollen im Quellcode-Repository.
|
||||
269
backups/docs-backup-20250731125004/framework/analytics/usage.md
Normal file
269
backups/docs-backup-20250731125004/framework/analytics/usage.md
Normal file
@@ -0,0 +1,269 @@
|
||||
# Analytics-Framework: Anwendungsbeispiele
|
||||
|
||||
## Grundlegende Verwendung
|
||||
|
||||
### Events tracken
|
||||
|
||||
```php
|
||||
// Über Dependency Injection
|
||||
public function __construct(private readonly Analytics $analytics) {}
|
||||
|
||||
// Einfaches Event tracken
|
||||
$this->analytics->track('login_attempt', [
|
||||
'success' => true,
|
||||
'user_type' => 'admin',
|
||||
'method' => 'password'
|
||||
]);
|
||||
|
||||
// Seitenaufruf tracken
|
||||
$this->analytics->page('/produkte/kategorie/elektronik', [
|
||||
'referrer' => 'homepage',
|
||||
'search_query' => 'smartphones'
|
||||
]);
|
||||
|
||||
// Benutzer identifizieren
|
||||
$this->analytics->user($user->getId(), [
|
||||
'email' => $user->getEmail(),
|
||||
'plan' => $user->getSubscriptionPlan(),
|
||||
'registered_since' => $user->getCreatedAt()->format('Y-m-d')
|
||||
]);
|
||||
```
|
||||
|
||||
### Fehler tracken
|
||||
|
||||
```php
|
||||
try {
|
||||
// Fehleranfälliger Code
|
||||
$result = $this->riskyOperation();
|
||||
return $result;
|
||||
} catch (\Exception $e) {
|
||||
// Fehler tracken
|
||||
$this->analytics->error($e);
|
||||
|
||||
// Fehler behandeln
|
||||
$this->logger->error($e->getMessage());
|
||||
return $this->fallbackOperation();
|
||||
}
|
||||
```
|
||||
|
||||
### Performance tracken
|
||||
|
||||
```php
|
||||
// Manuelles Performance-Tracking
|
||||
$startTime = microtime(true);
|
||||
$startMemory = memory_get_usage();
|
||||
|
||||
// Operation durchführen
|
||||
$result = $this->heavyOperation();
|
||||
|
||||
// Performance-Metriken tracken
|
||||
$this->analytics->performance([
|
||||
'operation' => 'heavy_operation',
|
||||
'execution_time' => microtime(true) - $startTime,
|
||||
'memory_used' => memory_get_usage() - $startMemory,
|
||||
'result_size' => is_countable($result) ? count($result) : 0
|
||||
]);
|
||||
```
|
||||
|
||||
## Erweiterte Anwendungsfälle
|
||||
|
||||
### Benutzerdefinierte Middleware
|
||||
|
||||
```php
|
||||
// In einem Service Provider oder Initializer
|
||||
public function initialize(AnalyticsManager $manager): void
|
||||
{
|
||||
// DSGVO-Middleware zur Anonymisierung personenbezogener Daten
|
||||
$manager->addMiddleware(function(array $event) {
|
||||
// E-Mail-Adressen anonymisieren
|
||||
if (isset($event['properties']['email'])) {
|
||||
$parts = explode('@', $event['properties']['email']);
|
||||
if (count($parts) === 2) {
|
||||
$event['properties']['email'] = substr($parts[0], 0, 1) .
|
||||
'***@' . $parts[1];
|
||||
}
|
||||
}
|
||||
|
||||
// Passwörter und Tokens entfernen
|
||||
foreach (['password', 'token', 'api_key', 'secret'] as $key) {
|
||||
if (isset($event['properties'][$key])) {
|
||||
$event['properties'][$key] = '[redacted]';
|
||||
}
|
||||
}
|
||||
|
||||
return $event;
|
||||
});
|
||||
|
||||
// Spam-Filter
|
||||
$manager->addMiddleware(function(array $event) {
|
||||
// Zu viele Events von einem Benutzer filtern
|
||||
static $userCounts = [];
|
||||
$userId = $event['user_id'] ?? $event['session_id'] ?? null;
|
||||
|
||||
if ($userId) {
|
||||
$userCounts[$userId] = ($userCounts[$userId] ?? 0) + 1;
|
||||
|
||||
// Mehr als 100 Events pro Session ist verdächtig
|
||||
if ($userCounts[$userId] > 100) {
|
||||
return null; // Event verwerfen
|
||||
}
|
||||
}
|
||||
|
||||
return $event;
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Integration mit dem Domain-Layer
|
||||
|
||||
```php
|
||||
// In einem Domain-Service
|
||||
namespace App\Domain\Shop\Services;
|
||||
|
||||
use App\Framework\Analytics\Analytics;
|
||||
|
||||
class ProductService
|
||||
{
|
||||
public function __construct(private readonly Analytics $analytics) {}
|
||||
|
||||
public function viewProduct(string $productId, ?string $userId): Product
|
||||
{
|
||||
$product = $this->productRepository->find($productId);
|
||||
|
||||
if (!$product) {
|
||||
throw new ProductNotFoundException($productId);
|
||||
}
|
||||
|
||||
// Produktansicht tracken
|
||||
$this->analytics->track('product_view', [
|
||||
'product_id' => $product->getId(),
|
||||
'product_name' => $product->getName(),
|
||||
'product_price' => $product->getPrice(),
|
||||
'product_category' => $product->getCategory()->getName(),
|
||||
'in_stock' => $product->isInStock()
|
||||
], $userId);
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
public function addToCart(string $productId, int $quantity, ?string $userId): Cart
|
||||
{
|
||||
// Implementation...
|
||||
|
||||
// Event tracken
|
||||
$this->analytics->track('add_to_cart', [
|
||||
'product_id' => $productId,
|
||||
'quantity' => $quantity,
|
||||
'cart_value' => $cart->getTotalValue()
|
||||
], $userId);
|
||||
|
||||
return $cart;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Verwendung im Controller
|
||||
|
||||
```php
|
||||
namespace App\Application\Controllers;
|
||||
|
||||
use App\Framework\Analytics\Analytics;
|
||||
use App\Framework\Http\Request;
|
||||
use App\Framework\Http\Response;
|
||||
use App\Framework\Attributes\Route;
|
||||
|
||||
class CheckoutController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Analytics $analytics,
|
||||
private readonly CheckoutService $checkoutService
|
||||
) {}
|
||||
|
||||
#[Route('/checkout/complete', method: 'POST')]
|
||||
public function completeCheckout(Request $request): Response
|
||||
{
|
||||
$userId = $request->getSession()->get('user_id');
|
||||
$cartId = $request->getSession()->get('cart_id');
|
||||
|
||||
try {
|
||||
$order = $this->checkoutService->completeCheckout($cartId, $userId);
|
||||
|
||||
// Erfolgreichen Checkout tracken
|
||||
$this->analytics->track('checkout_complete', [
|
||||
'order_id' => $order->getId(),
|
||||
'order_value' => $order->getTotalValue(),
|
||||
'items_count' => count($order->getItems()),
|
||||
'payment_method' => $order->getPaymentMethod(),
|
||||
'shipping_method' => $order->getShippingMethod()
|
||||
], $userId);
|
||||
|
||||
return new Response([
|
||||
'success' => true,
|
||||
'order_id' => $order->getId()
|
||||
], 200);
|
||||
} catch (\Exception $e) {
|
||||
// Fehler beim Checkout tracken
|
||||
$this->analytics->track('checkout_error', [
|
||||
'error' => $e->getMessage(),
|
||||
'cart_id' => $cartId
|
||||
], $userId);
|
||||
|
||||
// Auch den Exception-Stack tracken
|
||||
$this->analytics->error($e);
|
||||
|
||||
return new Response([
|
||||
'success' => false,
|
||||
'error' => $e->getMessage()
|
||||
], 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Analyse der Daten
|
||||
|
||||
### Dashboard-Controller
|
||||
|
||||
```php
|
||||
namespace App\Application\Controllers;
|
||||
|
||||
use App\Framework\Analytics\AnalyticsDashboard;
|
||||
use App\Framework\Http\Request;
|
||||
use App\Framework\Http\Response;
|
||||
use App\Framework\View\ViewRenderer;
|
||||
use App\Framework\Attributes\Route;
|
||||
|
||||
class AnalyticsDashboardController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AnalyticsDashboard $dashboard,
|
||||
private readonly ViewRenderer $viewRenderer
|
||||
) {}
|
||||
|
||||
#[Route('/admin/analytics/conversion')]
|
||||
public function conversionReport(Request $request): Response
|
||||
{
|
||||
$from = $request->getQueryParam('from');
|
||||
$to = $request->getQueryParam('to');
|
||||
|
||||
// Benutzerdefinierte Analyse für Conversion-Funnel
|
||||
$pageViews = $this->dashboard->getEventCountByType('page_view', $from, $to);
|
||||
$productViews = $this->dashboard->getEventCountByType('product_view', $from, $to);
|
||||
$addToCarts = $this->dashboard->getEventCountByType('add_to_cart', $from, $to);
|
||||
$checkouts = $this->dashboard->getEventCountByType('checkout_complete', $from, $to);
|
||||
|
||||
// Conversion-Raten berechnen
|
||||
$data = [
|
||||
'total_visitors' => $pageViews,
|
||||
'product_view_rate' => $pageViews > 0 ? $productViews / $pageViews : 0,
|
||||
'add_to_cart_rate' => $productViews > 0 ? $addToCarts / $productViews : 0,
|
||||
'checkout_rate' => $addToCarts > 0 ? $checkouts / $addToCarts : 0,
|
||||
'overall_conversion' => $pageViews > 0 ? $checkouts / $pageViews : 0,
|
||||
'from_date' => $from,
|
||||
'to_date' => $to
|
||||
];
|
||||
|
||||
return $this->viewRenderer->render('admin/analytics/conversion', $data);
|
||||
}
|
||||
}
|
||||
```
|
||||
45
backups/docs-backup-20250731125004/framework/core/README.md
Normal file
45
backups/docs-backup-20250731125004/framework/core/README.md
Normal file
@@ -0,0 +1,45 @@
|
||||
# Core-Modul Dokumentation
|
||||
|
||||
## Übersicht
|
||||
|
||||
Das Core-Modul bildet das Herzstück des Frameworks und stellt grundlegende Funktionalitäten bereit, die von anderen Modulen genutzt werden.
|
||||
|
||||
## Hauptkomponenten
|
||||
|
||||
### Events und EventDispatcher
|
||||
|
||||
Das Event-System ermöglicht die Kommunikation zwischen Komponenten über einen zentralen Event-Bus.
|
||||
|
||||
**Kernklassen:**
|
||||
- `EventDispatcher`: Zentraler Service zum Registrieren und Auslösen von Events
|
||||
- Bekannte Events:
|
||||
- `ApplicationBooted`
|
||||
- `ErrorOccurred`
|
||||
- `BeforeHandleRequest`
|
||||
- `AfterHandleRequest`
|
||||
|
||||
**Beispielverwendung:**
|
||||
```php
|
||||
// Event-Handler registrieren
|
||||
$eventDispatcher->addHandler('App\Framework\Core\Events\ApplicationBooted', function($event) {
|
||||
// Event verarbeiten
|
||||
});
|
||||
```
|
||||
|
||||
### PathProvider
|
||||
|
||||
Stellt Pfadinformationen für verschiedene Bereiche der Anwendung bereit.
|
||||
|
||||
**Hauptfunktionen:**
|
||||
- `getDataPath()`: Liefert Pfade zu Datenverzeichnissen
|
||||
|
||||
## Integration mit anderen Modulen
|
||||
|
||||
Das Core-Modul wird von vielen anderen Modulen verwendet, wie z.B.:
|
||||
|
||||
- **Analytics-Modul**: Nutzt den EventDispatcher zum Tracking von Systemereignissen
|
||||
- **DI-Container**: Nutzt Core-Komponenten für die Initialisierung von Services
|
||||
|
||||
## Architektur
|
||||
|
||||
Das Core-Modul folgt einer ereignisgesteuerten Architektur, bei der Komponenten über Events miteinander kommunizieren können, anstatt direkte Abhängigkeiten zu haben.
|
||||
89
backups/docs-backup-20250731125004/framework/di/README.md
Normal file
89
backups/docs-backup-20250731125004/framework/di/README.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# Dependency Injection Modul
|
||||
|
||||
## Übersicht
|
||||
|
||||
Das DI-Modul implementiert ein Dependency-Injection-Container-System, das die automatische Auflösung und Verwaltung von Abhängigkeiten ermöglicht.
|
||||
|
||||
## Hauptkomponenten
|
||||
|
||||
### Container
|
||||
|
||||
Der zentrale Service-Container, der Instanzen erstellt und verwaltet.
|
||||
|
||||
**Hauptfunktionen:**
|
||||
- Service-Erstellung und -Auflösung
|
||||
- Singleton-Verwaltung
|
||||
- Rekursive Abhängigkeitsauflösung
|
||||
|
||||
### Initializer-Attribut
|
||||
|
||||
Das `#[Initializer]`-Attribut kennzeichnet Klassen, die Services im Container registrieren können.
|
||||
|
||||
**Beispiel:**
|
||||
```php
|
||||
#[Initializer]
|
||||
readonly class AnalyticsInitializer
|
||||
{
|
||||
public function __invoke(Container $container): Analytics
|
||||
{
|
||||
// Service erstellen und konfigurieren
|
||||
return $analytics;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Verwendung
|
||||
|
||||
### Service definieren
|
||||
|
||||
```php
|
||||
// Service-Interface
|
||||
interface MyServiceInterface
|
||||
{
|
||||
public function doSomething(): void;
|
||||
}
|
||||
|
||||
// Konkrete Implementierung
|
||||
class MyService implements MyServiceInterface
|
||||
{
|
||||
public function doSomething(): void
|
||||
{
|
||||
// Implementierung
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Service registrieren
|
||||
|
||||
```php
|
||||
#[Initializer]
|
||||
class MyServiceInitializer
|
||||
{
|
||||
public function __invoke(Container $container): MyServiceInterface
|
||||
{
|
||||
return new MyService();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Service verwenden
|
||||
|
||||
```php
|
||||
class MyController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly MyServiceInterface $myService
|
||||
) {}
|
||||
|
||||
public function action(): void
|
||||
{
|
||||
$this->myService->doSomething();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Prinzipien
|
||||
|
||||
- **Automatische Auflösung**: Abhängigkeiten werden anhand von Typ-Hints automatisch aufgelöst
|
||||
- **Lazy Loading**: Services werden erst erstellt, wenn sie benötigt werden
|
||||
- **Singleton-Modus**: Standardmäßig werden Services als Singletons verwaltet
|
||||
439
backups/docs-backup-20250731125004/framework/error-boundaries.md
Normal file
439
backups/docs-backup-20250731125004/framework/error-boundaries.md
Normal file
@@ -0,0 +1,439 @@
|
||||
# Error Boundaries
|
||||
|
||||
Error Boundaries provide graceful degradation and prevent cascading failures in the application. They act as a safety net that catches errors and provides fallback functionality instead of letting the entire system fail.
|
||||
|
||||
## Overview
|
||||
|
||||
The Error Boundary system implements multiple patterns for resilient error handling:
|
||||
|
||||
- **Fallback Mechanisms** - Provide alternative functionality when operations fail
|
||||
- **Retry Strategies** - Automatically retry failed operations with configurable strategies
|
||||
- **Circuit Breaker Pattern** - Prevent repeated calls to failing services
|
||||
- **Bulk Operations** - Handle partial failures in batch processing
|
||||
- **Timeout Protection** - Prevent long-running operations from blocking the system
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Simple Error Boundary
|
||||
|
||||
```php
|
||||
use App\Framework\ErrorBoundaries\ErrorBoundary;
|
||||
use App\Framework\ErrorBoundaries\BoundaryConfig;
|
||||
|
||||
$boundary = new ErrorBoundary('user_service', BoundaryConfig::externalService());
|
||||
|
||||
$result = $boundary->execute(
|
||||
operation: fn() => $userService->getUser($id),
|
||||
fallback: fn() => $this->getCachedUser($id)
|
||||
);
|
||||
```
|
||||
|
||||
### Factory Pattern
|
||||
|
||||
```php
|
||||
use App\Framework\ErrorBoundaries\ErrorBoundaryFactory;
|
||||
|
||||
$factory = $container->get(ErrorBoundaryFactory::class);
|
||||
|
||||
// Create boundary for different contexts
|
||||
$dbBoundary = $factory->createForDatabase('user_queries');
|
||||
$apiBoundary = $factory->createForExternalService('payment_api');
|
||||
$uiBoundary = $factory->createForUI('user_dashboard');
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Predefined Configurations
|
||||
|
||||
```php
|
||||
// Critical operations - maximum resilience
|
||||
BoundaryConfig::critical()
|
||||
|
||||
// External services - network-aware retries
|
||||
BoundaryConfig::externalService()
|
||||
|
||||
// Database operations - transaction-safe retries
|
||||
BoundaryConfig::database()
|
||||
|
||||
// UI components - fast failure for user experience
|
||||
BoundaryConfig::ui()
|
||||
|
||||
// Background jobs - long retry cycles
|
||||
BoundaryConfig::backgroundJob()
|
||||
|
||||
// Development - permissive for debugging
|
||||
BoundaryConfig::development()
|
||||
|
||||
// Fail fast - no retries
|
||||
BoundaryConfig::failFast()
|
||||
```
|
||||
|
||||
### Custom Configuration
|
||||
|
||||
```php
|
||||
$config = new BoundaryConfig(
|
||||
maxRetries: 3,
|
||||
retryStrategy: RetryStrategy::EXPONENTIAL_JITTER,
|
||||
baseDelay: Duration::fromMilliseconds(100),
|
||||
maxDelay: Duration::fromSeconds(5),
|
||||
circuitBreakerEnabled: true,
|
||||
circuitBreakerThreshold: 5,
|
||||
circuitBreakerTimeout: Duration::fromMinutes(1),
|
||||
maxBulkErrorRate: 0.3,
|
||||
enableMetrics: true,
|
||||
enableTracing: false
|
||||
);
|
||||
```
|
||||
|
||||
## Execution Strategies
|
||||
|
||||
### Standard Execution with Fallback
|
||||
|
||||
```php
|
||||
$result = $boundary->execute(
|
||||
operation: fn() => $service->riskyOperation(),
|
||||
fallback: fn() => $service->safeAlternative()
|
||||
);
|
||||
```
|
||||
|
||||
### Optional Execution (Returns null on failure)
|
||||
|
||||
```php
|
||||
$result = $boundary->executeOptional(
|
||||
operation: fn() => $service->optionalOperation(),
|
||||
fallback: fn() => $service->defaultValue() // Optional fallback
|
||||
);
|
||||
```
|
||||
|
||||
### Default Value on Failure
|
||||
|
||||
```php
|
||||
$result = $boundary->executeWithDefault(
|
||||
operation: fn() => $service->getValue(),
|
||||
defaultValue: 'default_value'
|
||||
);
|
||||
```
|
||||
|
||||
### Result Wrapper
|
||||
|
||||
```php
|
||||
$result = $boundary->executeForResult(
|
||||
operation: fn() => $service->operation()
|
||||
);
|
||||
|
||||
if ($result->isSuccess()) {
|
||||
$value = $result->getValue();
|
||||
} else {
|
||||
$error = $result->getError();
|
||||
}
|
||||
```
|
||||
|
||||
## Retry Strategies
|
||||
|
||||
### Fixed Delay
|
||||
|
||||
```php
|
||||
RetryStrategy::FIXED // Same delay between retries
|
||||
```
|
||||
|
||||
### Linear Backoff
|
||||
|
||||
```php
|
||||
RetryStrategy::LINEAR // Linearly increasing delay
|
||||
```
|
||||
|
||||
### Exponential Backoff
|
||||
|
||||
```php
|
||||
RetryStrategy::EXPONENTIAL // Exponentially increasing delay
|
||||
```
|
||||
|
||||
### Exponential with Jitter
|
||||
|
||||
```php
|
||||
RetryStrategy::EXPONENTIAL_JITTER // Exponential + random jitter
|
||||
```
|
||||
|
||||
## Circuit Breaker Pattern
|
||||
|
||||
```php
|
||||
$config = new BoundaryConfig(
|
||||
circuitBreakerEnabled: true,
|
||||
circuitBreakerThreshold: 5, // Open after 5 failures
|
||||
circuitBreakerTimeout: Duration::fromMinutes(2) // Try again after 2 minutes
|
||||
);
|
||||
|
||||
$result = $boundary->executeWithCircuitBreaker(
|
||||
operation: fn() => $externalService->call(),
|
||||
fallback: fn() => $this->getCachedResponse()
|
||||
);
|
||||
```
|
||||
|
||||
## Bulk Operations
|
||||
|
||||
Handle batch processing with partial failure tolerance:
|
||||
|
||||
```php
|
||||
$items = [1, 2, 3, 4, 5];
|
||||
|
||||
$result = $boundary->executeBulk($items, function($item) {
|
||||
if ($item % 2 === 0) {
|
||||
throw new Exception("Even numbers fail");
|
||||
}
|
||||
return $item * 2;
|
||||
});
|
||||
|
||||
echo "Processed: {$result->getProcessedCount()}/{$result->getTotalCount()}\n";
|
||||
echo "Success rate: {$result->getSuccessRate()}%\n";
|
||||
|
||||
foreach ($result->getResults() as $key => $value) {
|
||||
echo "Item {$key}: {$value}\n";
|
||||
}
|
||||
|
||||
foreach ($result->getErrors() as $key => $error) {
|
||||
echo "Error {$key}: {$error->getMessage()}\n";
|
||||
}
|
||||
```
|
||||
|
||||
## Timeout Protection
|
||||
|
||||
```php
|
||||
$result = $boundary->executeWithTimeout(
|
||||
operation: fn() => $longRunningService->process(),
|
||||
fallback: fn() => 'Operation timed out',
|
||||
timeoutSeconds: 30
|
||||
);
|
||||
```
|
||||
|
||||
## Parallel Operations
|
||||
|
||||
Execute multiple operations with individual boundaries:
|
||||
|
||||
```php
|
||||
$operations = [
|
||||
'user_data' => fn() => $userService->getData(),
|
||||
'preferences' => fn() => $prefsService->getPreferences(),
|
||||
'notifications' => fn() => $notificationService->getCount()
|
||||
];
|
||||
|
||||
$results = $boundary->executeParallel($operations);
|
||||
|
||||
foreach ($results as $name => $result) {
|
||||
if ($result->isSuccess()) {
|
||||
$data[$name] = $result->getValue();
|
||||
} else {
|
||||
$data[$name] = null; // Or default value
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## HTTP Middleware Integration
|
||||
|
||||
Automatic error boundary protection for HTTP requests:
|
||||
|
||||
```php
|
||||
// In middleware registration
|
||||
$app->addMiddleware(ErrorBoundaryMiddleware::class);
|
||||
```
|
||||
|
||||
The middleware automatically:
|
||||
- Creates boundaries based on route patterns
|
||||
- Provides JSON fallback responses for API routes
|
||||
- Provides HTML error pages for web routes
|
||||
- Logs failures for monitoring
|
||||
|
||||
## Environment Configuration
|
||||
|
||||
Configure boundaries via environment variables:
|
||||
|
||||
```env
|
||||
# Global settings
|
||||
ERROR_BOUNDARY_ENABLED=true
|
||||
|
||||
# Route-specific configuration
|
||||
ERROR_BOUNDARY_ROUTE_API_USER_MAX_RETRIES=5
|
||||
ERROR_BOUNDARY_ROUTE_API_USER_CIRCUIT_BREAKER_ENABLED=true
|
||||
ERROR_BOUNDARY_ROUTE_API_USER_BASE_DELAY_MS=200
|
||||
```
|
||||
|
||||
## Console Commands
|
||||
|
||||
### Test Error Boundaries
|
||||
|
||||
```bash
|
||||
# Test basic functionality
|
||||
php console.php boundary:test basic
|
||||
|
||||
# Test retry strategies
|
||||
php console.php boundary:test retry
|
||||
|
||||
# Test circuit breaker
|
||||
php console.php boundary:test circuit
|
||||
|
||||
# Test bulk operations
|
||||
php console.php boundary:test bulk
|
||||
```
|
||||
|
||||
### Monitor Circuit Breakers
|
||||
|
||||
```bash
|
||||
# Show circuit breaker statistics
|
||||
php console.php boundary:stats
|
||||
|
||||
# Reset specific circuit breaker
|
||||
php console.php boundary:reset user_service
|
||||
|
||||
# Reset all circuit breakers
|
||||
php console.php boundary:reset
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Choose Appropriate Configurations
|
||||
|
||||
```php
|
||||
// API endpoints - use external service config
|
||||
$apiBoundary = $factory->createForExternalService('payment_api');
|
||||
|
||||
// Database queries - use database config
|
||||
$dbBoundary = $factory->createForDatabase('user_queries');
|
||||
|
||||
// UI components - use UI config for fast failures
|
||||
$uiBoundary = $factory->createForUI('dashboard_widget');
|
||||
```
|
||||
|
||||
### 2. Meaningful Fallbacks
|
||||
|
||||
```php
|
||||
// Good - provides useful fallback
|
||||
$boundary->execute(
|
||||
operation: fn() => $service->getLiveData(),
|
||||
fallback: fn() => $service->getCachedData()
|
||||
);
|
||||
|
||||
// Avoid - fallback provides no value
|
||||
$boundary->execute(
|
||||
operation: fn() => $service->getData(),
|
||||
fallback: fn() => null
|
||||
);
|
||||
```
|
||||
|
||||
### 3. Monitor Circuit Breakers
|
||||
|
||||
```php
|
||||
// Set up alerting for circuit breaker state changes
|
||||
$boundary->executeWithCircuitBreaker(
|
||||
operation: fn() => $service->call(),
|
||||
fallback: function() {
|
||||
$this->logger->warning('Circuit breaker activated for service');
|
||||
return $this->getFallbackData();
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### 4. Handle Bulk Operations Appropriately
|
||||
|
||||
```php
|
||||
$result = $boundary->executeBulk($items, $processor);
|
||||
|
||||
// Check if too many failures occurred
|
||||
if ($result->getErrorRate() > 50) {
|
||||
$this->logger->error('High error rate in bulk operation');
|
||||
// Consider stopping or alerting
|
||||
}
|
||||
```
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With Repositories
|
||||
|
||||
```php
|
||||
class UserRepository
|
||||
{
|
||||
public function __construct(
|
||||
private ErrorBoundaryFactory $boundaryFactory,
|
||||
private DatabaseConnection $db
|
||||
) {}
|
||||
|
||||
public function findById(int $id): ?User
|
||||
{
|
||||
$boundary = $this->boundaryFactory->createForDatabase('user_find');
|
||||
|
||||
return $boundary->executeOptional(
|
||||
operation: fn() => $this->db->query('SELECT * FROM users WHERE id = ?', [$id]),
|
||||
fallback: fn() => $this->getCachedUser($id)
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### With External APIs
|
||||
|
||||
```php
|
||||
class PaymentService
|
||||
{
|
||||
public function processPayment(Payment $payment): PaymentResult
|
||||
{
|
||||
$boundary = $this->boundaryFactory->createForExternalService('payment_gateway');
|
||||
|
||||
return $boundary->execute(
|
||||
operation: fn() => $this->gateway->process($payment),
|
||||
fallback: fn() => $this->queueForLaterProcessing($payment)
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### With Background Jobs
|
||||
|
||||
```php
|
||||
class EmailJob
|
||||
{
|
||||
public function handle(): void
|
||||
{
|
||||
$boundary = $this->boundaryFactory->createForBackgroundJob('email_sending');
|
||||
|
||||
$boundary->executeBulk($this->emails, function($email) {
|
||||
$this->mailer->send($email);
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
Error boundaries can throw specific exceptions:
|
||||
|
||||
- `BoundaryFailedException` - When both operation and fallback fail
|
||||
- `BoundaryTimeoutException` - When operations exceed timeout limits
|
||||
|
||||
```php
|
||||
try {
|
||||
$result = $boundary->execute($operation, $fallback);
|
||||
} catch (BoundaryFailedException $e) {
|
||||
$this->logger->error('Boundary failed completely', [
|
||||
'boundary' => $e->getBoundaryName(),
|
||||
'original_error' => $e->getOriginalException()?->getMessage(),
|
||||
'fallback_error' => $e->getFallbackException()?->getMessage(),
|
||||
]);
|
||||
} catch (BoundaryTimeoutException $e) {
|
||||
$this->logger->warning('Operation timed out', [
|
||||
'boundary' => $e->getBoundaryName(),
|
||||
'execution_time' => $e->getExecutionTime(),
|
||||
'timeout_limit' => $e->getTimeoutLimit(),
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
1. **Circuit Breakers** - Use file-based storage for simplicity, consider Redis for high-traffic applications
|
||||
2. **Retry Delays** - Use jitter to avoid thundering herd problems
|
||||
3. **Bulk Operations** - Set appropriate error rate thresholds to prevent resource exhaustion
|
||||
4. **Timeouts** - PHP's synchronous nature limits true timeout implementation
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **Information Disclosure** - Ensure fallbacks don't leak sensitive information
|
||||
2. **Resource Exhaustion** - Configure appropriate timeouts and retry limits
|
||||
3. **Circuit Breaker State** - Protect circuit breaker state files from unauthorized access
|
||||
521
backups/docs-backup-20250731125004/framework/error-reporting.md
Normal file
521
backups/docs-backup-20250731125004/framework/error-reporting.md
Normal file
@@ -0,0 +1,521 @@
|
||||
# Error Reporting & Analytics
|
||||
|
||||
Das Error Reporting System bietet strukturierte Fehlerberichterstattung und erweiterte Analytics für das Framework. Es erfasst, analysiert und visualisiert Fehler mit umfassendem Kontext für bessere Debugging- und Monitoring-Möglichkeiten.
|
||||
|
||||
## Überblick
|
||||
|
||||
Das System implementiert folgende Funktionen:
|
||||
|
||||
- **Strukturierte Fehlerberichte** - Umfassende Kontext-Erfassung
|
||||
- **Analytics Engine** - Trend-Analyse und Anomalie-Erkennung
|
||||
- **Predictive Insights** - Vorhersagen und Empfehlungen
|
||||
- **Context Processors** - Automatische Anreicherung mit Request/User-Kontext
|
||||
- **Storage Interface** - Flexible Speicher-Implementierungen
|
||||
- **Console Commands** - Management und Monitoring Tools
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Error Reporter
|
||||
|
||||
```php
|
||||
use App\Framework\ErrorReporting\ErrorReporter;
|
||||
|
||||
$reporter = $container->get(ErrorReporter::class);
|
||||
|
||||
// Report an exception
|
||||
$reportId = $reporter->reportThrowable($exception);
|
||||
|
||||
// Report manual error
|
||||
$reportId = $reporter->reportError('error', 'Something went wrong', [
|
||||
'user_action' => 'delete_file',
|
||||
'file_id' => 123
|
||||
]);
|
||||
```
|
||||
|
||||
### Mit Request Context
|
||||
|
||||
```php
|
||||
$contextualReporter = $reporter->withRequestContext(
|
||||
method: 'POST',
|
||||
route: '/api/users',
|
||||
requestId: $requestId,
|
||||
userAgent: $userAgent,
|
||||
ipAddress: $clientIp
|
||||
);
|
||||
|
||||
$reportId = $contextualReporter->reportThrowable($exception);
|
||||
```
|
||||
|
||||
### Mit User Context
|
||||
|
||||
```php
|
||||
$userReporter = $reporter->withUserContext(
|
||||
userId: $user->getId(),
|
||||
sessionId: $session->getId()
|
||||
);
|
||||
|
||||
$reportId = $userReporter->reportError('warning', 'User action failed');
|
||||
```
|
||||
|
||||
## Error Report Structure
|
||||
|
||||
```php
|
||||
$report = ErrorReport::fromThrowable($exception)
|
||||
->withUser($userId, $sessionId)
|
||||
->withRequest($method, $route, $requestId, $userAgent, $ipAddress)
|
||||
->withPerformance($executionTime, $memoryUsage)
|
||||
->withTags(['api', 'payment'])
|
||||
->withBreadcrumbs($breadcrumbs)
|
||||
->withCustomData(['order_id' => 12345]);
|
||||
```
|
||||
|
||||
### Report Properties
|
||||
|
||||
- **Basic Info**: ID, timestamp, level, message, exception class
|
||||
- **Location**: File, line, stack trace
|
||||
- **User Context**: User ID, session ID
|
||||
- **Request Context**: Route, method, IP, user agent, request data
|
||||
- **Performance**: Execution time, memory usage
|
||||
- **Metadata**: Tags, breadcrumbs, custom data, environment info
|
||||
- **Analytics**: Fingerprint, severity level
|
||||
|
||||
## Analytics Engine
|
||||
|
||||
### Anomalie-Erkennung
|
||||
|
||||
```php
|
||||
use App\Framework\ErrorReporting\Analytics\ErrorAnalyticsEngine;
|
||||
|
||||
$analytics = $container->get(ErrorAnalyticsEngine::class);
|
||||
|
||||
$from = new DateTimeImmutable('-24 hours');
|
||||
$to = new DateTimeImmutable();
|
||||
|
||||
// Detect anomalies and spikes
|
||||
$anomalies = $analytics->detectAnomalies($from, $to);
|
||||
|
||||
foreach ($anomalies as $anomaly) {
|
||||
echo "Anomaly detected: {$anomaly['type']} at {$anomaly['period']}\n";
|
||||
echo "Count: {$anomaly['count']} (expected: {$anomaly['expected']})\n";
|
||||
echo "Z-Score: {$anomaly['z_score']}\n";
|
||||
}
|
||||
```
|
||||
|
||||
### Error Velocity
|
||||
|
||||
```php
|
||||
// Calculate rate of change
|
||||
$velocity = $analytics->calculateErrorVelocity($from, $to);
|
||||
|
||||
$latest = end($velocity);
|
||||
echo "Latest trend: {$latest['direction']} ({$latest['velocity_percent']}%)\n";
|
||||
```
|
||||
|
||||
### Pattern Analysis
|
||||
|
||||
```php
|
||||
$patterns = $analytics->identifyPatterns($from, $to);
|
||||
|
||||
// Route correlations
|
||||
foreach ($patterns['route_correlations'] as $correlation) {
|
||||
echo "Route {$correlation['route']}: {$correlation['total_errors']} errors\n";
|
||||
echo "Clustered periods: {$correlation['clustered_periods']}\n";
|
||||
}
|
||||
|
||||
// Time patterns
|
||||
$timePatterns = $patterns['time_patterns'];
|
||||
echo "Peak hour: {$timePatterns['peak_hour']}\n";
|
||||
echo "Peak day: {$timePatterns['peak_day']}\n";
|
||||
```
|
||||
|
||||
### Predictive Insights
|
||||
|
||||
```php
|
||||
$predictions = $analytics->generatePredictiveInsights($from, $to);
|
||||
|
||||
$trend = $predictions['trend_prediction'];
|
||||
echo "Trend: {$trend['trend']} (slope: {$trend['slope']})\n";
|
||||
|
||||
foreach ($trend['predictions'] as $prediction) {
|
||||
echo "Period +{$prediction['period']}: ~{$prediction['predicted_count']} errors\n";
|
||||
}
|
||||
|
||||
$risk = $predictions['risk_assessment'];
|
||||
echo "Risk level: {$risk['level']} (factor: {$risk['risk_factor']})\n";
|
||||
```
|
||||
|
||||
### Health Report
|
||||
|
||||
```php
|
||||
$healthReport = $analytics->generateHealthReport($from, $to);
|
||||
|
||||
echo "Health Score: {$healthReport['health_score']}/100\n";
|
||||
|
||||
// Impact analysis
|
||||
$impact = $healthReport['impact'];
|
||||
echo "Affected users: {$impact['user_impact']['affected_users']}\n";
|
||||
echo "Critical errors: {$impact['business_impact']['critical_errors']}\n";
|
||||
|
||||
// Recommendations
|
||||
foreach ($healthReport['predictions']['recommendations'] as $rec) {
|
||||
echo "[{$rec['priority']}] {$rec['message']}\n";
|
||||
}
|
||||
```
|
||||
|
||||
## Search & Filtering
|
||||
|
||||
```php
|
||||
use App\Framework\ErrorReporting\ErrorReportCriteria;
|
||||
|
||||
// Recent critical errors
|
||||
$criteria = ErrorReportCriteria::critical();
|
||||
$reports = $reporter->findReports($criteria);
|
||||
|
||||
// Errors by user
|
||||
$criteria = ErrorReportCriteria::byUser('user123');
|
||||
$reports = $reporter->findReports($criteria);
|
||||
|
||||
// Complex search
|
||||
$criteria = ErrorReportCriteria::recent(48) // Last 48 hours
|
||||
->withLevels(['error', 'critical'])
|
||||
->withEnvironment('production')
|
||||
->withPagination(50, 0);
|
||||
|
||||
$reports = $reporter->findReports($criteria);
|
||||
```
|
||||
|
||||
### Search Criteria Options
|
||||
|
||||
```php
|
||||
$criteria = new ErrorReportCriteria(
|
||||
from: $fromDate,
|
||||
to: $toDate,
|
||||
levels: ['error', 'critical'],
|
||||
exceptions: ['DatabaseException', 'PaymentException'],
|
||||
routes: ['/api/payment', '/api/orders'],
|
||||
methods: ['POST', 'PUT'],
|
||||
userId: 'user123',
|
||||
environment: 'production',
|
||||
tags: ['payment', 'critical'],
|
||||
search: 'connection timeout',
|
||||
fingerprint: 'abc123',
|
||||
minSeverity: 2,
|
||||
maxSeverity: 4,
|
||||
limit: 100,
|
||||
offset: 0,
|
||||
orderBy: 'timestamp',
|
||||
orderDir: 'DESC'
|
||||
);
|
||||
```
|
||||
|
||||
## Context Processors
|
||||
|
||||
### Request Context Processor
|
||||
|
||||
Automatische Anreicherung mit HTTP Request Informationen:
|
||||
|
||||
- Method, Route, User-Agent, IP-Adresse
|
||||
- Request Data (GET, POST, JSON) - sanitized
|
||||
- Execution Time, Memory Usage
|
||||
- Tags (API, AJAX, Method)
|
||||
|
||||
### User Context Processor
|
||||
|
||||
Automatische Anreicherung mit User Informationen:
|
||||
|
||||
- User ID aus Session
|
||||
- Session ID
|
||||
- User Breadcrumbs
|
||||
- Tags (authenticated/anonymous)
|
||||
|
||||
```php
|
||||
use App\Framework\ErrorReporting\Processors\UserContextProcessor;
|
||||
|
||||
// Add breadcrumb from application code
|
||||
UserContextProcessor::addBreadcrumb(
|
||||
message: 'User clicked delete button',
|
||||
category: 'user_action',
|
||||
level: 'info',
|
||||
data: ['file_id' => 123]
|
||||
);
|
||||
```
|
||||
|
||||
## HTTP Middleware
|
||||
|
||||
Automatische Fehlerberichterstattung für HTTP Requests:
|
||||
|
||||
```php
|
||||
// Automatically registered via initializer
|
||||
$app->addMiddleware(ErrorReportingMiddleware::class);
|
||||
```
|
||||
|
||||
Das Middleware:
|
||||
- Fängt alle ungefangenen Exceptions ab
|
||||
- Fügt Request-Kontext automatisch hinzu
|
||||
- Sanitized Request-Daten
|
||||
- Bestimmt Client IP korrekt (X-Forwarded-For, etc.)
|
||||
|
||||
## Console Commands
|
||||
|
||||
### Statistiken anzeigen
|
||||
|
||||
```bash
|
||||
# Last 24 hours (default)
|
||||
php console.php errors:stats
|
||||
|
||||
# Last 48 hours
|
||||
php console.php errors:stats 48
|
||||
```
|
||||
|
||||
Zeigt:
|
||||
- Total/Unique Errors
|
||||
- Critical Error Count
|
||||
- Error Rate & Health Score
|
||||
- Errors by Level
|
||||
- Top Exceptions & Routes
|
||||
- Insights & Recommendations
|
||||
|
||||
### Advanced Analytics
|
||||
|
||||
```bash
|
||||
# Advanced analytics report
|
||||
php console.php errors:analytics 24
|
||||
```
|
||||
|
||||
Zeigt:
|
||||
- Anomaly Detection
|
||||
- Error Velocity
|
||||
- Pattern Analysis
|
||||
- Predictive Insights
|
||||
|
||||
### Health Report
|
||||
|
||||
```bash
|
||||
# Comprehensive health report
|
||||
php console.php errors:health 24
|
||||
```
|
||||
|
||||
Zeigt:
|
||||
- Overall Health Score
|
||||
- Key Metrics
|
||||
- Impact Analysis
|
||||
- Recommendations
|
||||
|
||||
### Search Errors
|
||||
|
||||
```bash
|
||||
# Search by term
|
||||
php console.php errors:search "database connection"
|
||||
```
|
||||
|
||||
### Show Error Details
|
||||
|
||||
```bash
|
||||
# Show detailed error report
|
||||
php console.php errors:show <report-id>
|
||||
```
|
||||
|
||||
### Cleanup
|
||||
|
||||
```bash
|
||||
# Delete errors older than 30 days (default)
|
||||
php console.php errors:cleanup
|
||||
|
||||
# Delete errors older than 7 days
|
||||
php console.php errors:cleanup 7
|
||||
```
|
||||
|
||||
## Environment Configuration
|
||||
|
||||
```env
|
||||
# Enable/disable error reporting
|
||||
ERROR_REPORTING_ENABLED=true
|
||||
|
||||
# Enable async processing via queue
|
||||
ERROR_REPORTING_ASYNC=true
|
||||
|
||||
# Filter levels (comma-separated)
|
||||
ERROR_REPORTING_FILTER_LEVELS=error,critical,alert,emergency
|
||||
```
|
||||
|
||||
## Database Schema
|
||||
|
||||
Das System benötigt die `error_reports` Tabelle:
|
||||
|
||||
```bash
|
||||
php console.php db:migrate
|
||||
```
|
||||
|
||||
Die Migration erstellt eine optimierte Tabelle mit:
|
||||
- Primary Key: String ID (32 chars)
|
||||
- Indexes für häufige Queries
|
||||
- JSON Felder für flexible Daten
|
||||
- Analytics-Felder (fingerprint, severity_level)
|
||||
|
||||
## Storage Interface
|
||||
|
||||
Custom Storage Implementierungen möglich:
|
||||
|
||||
```php
|
||||
use App\Framework\ErrorReporting\Storage\ErrorReportStorageInterface;
|
||||
|
||||
class RedisErrorReportStorage implements ErrorReportStorageInterface
|
||||
{
|
||||
public function store(ErrorReport $report): void
|
||||
{
|
||||
// Custom implementation
|
||||
}
|
||||
|
||||
// ... other methods
|
||||
}
|
||||
|
||||
// In initializer
|
||||
$container->bind(ErrorReportStorageInterface::class, RedisErrorReportStorage::class);
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Structured Error Messages
|
||||
|
||||
```php
|
||||
// Good - structured context
|
||||
$reporter->reportError('error', 'Payment processing failed', [
|
||||
'payment_id' => $paymentId,
|
||||
'amount' => $amount,
|
||||
'currency' => $currency,
|
||||
'gateway_response' => $gatewayResponse
|
||||
]);
|
||||
|
||||
// Avoid - unstructured message
|
||||
$reporter->reportError('error', "Payment $paymentId failed for $amount $currency");
|
||||
```
|
||||
|
||||
### 2. Appropriate Log Levels
|
||||
|
||||
```php
|
||||
// Critical system failures
|
||||
$reporter->reportThrowable($exception, 'critical');
|
||||
|
||||
// Business logic errors
|
||||
$reporter->reportThrowable($exception, 'error');
|
||||
|
||||
// Recoverable issues
|
||||
$reporter->reportError('warning', 'Deprecated API used');
|
||||
|
||||
// Development info
|
||||
$reporter->reportError('info', 'Cache miss occurred');
|
||||
```
|
||||
|
||||
### 3. Sensitive Data Handling
|
||||
|
||||
```php
|
||||
// Data is automatically sanitized by processors
|
||||
// But be explicit about sensitive data
|
||||
$reporter->reportError('error', 'Authentication failed', [
|
||||
'username' => $username,
|
||||
'ip_address' => $ip,
|
||||
// Don't include: password, tokens, etc.
|
||||
]);
|
||||
```
|
||||
|
||||
### 4. Custom Tags for Filtering
|
||||
|
||||
```php
|
||||
$report = ErrorReport::fromThrowable($exception)
|
||||
->withTags(['payment', 'external_api', 'critical']);
|
||||
```
|
||||
|
||||
### 5. Breadcrumbs for Context
|
||||
|
||||
```php
|
||||
// Add breadcrumbs throughout user journey
|
||||
UserContextProcessor::addBreadcrumb('User logged in');
|
||||
UserContextProcessor::addBreadcrumb('Started checkout process');
|
||||
UserContextProcessor::addBreadcrumb('Selected payment method', 'action', 'info', [
|
||||
'method' => 'credit_card'
|
||||
]);
|
||||
|
||||
// Error report will include full journey
|
||||
```
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
1. **Async Processing** - Enable für Production (`ERROR_REPORTING_ASYNC=true`)
|
||||
2. **Data Sanitization** - Automatic für Request Data
|
||||
3. **Storage Optimization** - Indexes für häufige Queries
|
||||
4. **Cleanup Strategy** - Regular cleanup alter Reports
|
||||
5. **Memory Usage** - Limited Context Data Size
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **Data Sanitization** - Sensitive Data wird automatisch entfernt
|
||||
2. **Access Control** - Console Commands benötigen entsprechende Rechte
|
||||
3. **Storage Security** - Database Access Controls
|
||||
4. **IP Address Handling** - Respects Privacy Regulations
|
||||
5. **Session Security** - Nur Session IDs, keine Session Daten
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### Mit Custom Exception Handler
|
||||
|
||||
```php
|
||||
class CustomExceptionHandler
|
||||
{
|
||||
public function __construct(
|
||||
private ErrorReporter $reporter
|
||||
) {}
|
||||
|
||||
public function handle(Throwable $exception): void
|
||||
{
|
||||
// Report the error
|
||||
$this->reporter->reportThrowable($exception);
|
||||
|
||||
// Continue with normal error handling
|
||||
$this->originalHandler->handle($exception);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Mit Business Logic
|
||||
|
||||
```php
|
||||
class PaymentService
|
||||
{
|
||||
public function processPayment(Payment $payment): PaymentResult
|
||||
{
|
||||
try {
|
||||
return $this->gateway->process($payment);
|
||||
} catch (PaymentException $e) {
|
||||
// Report with business context
|
||||
$this->reporter->reportThrowable($e, 'error', [
|
||||
'payment_id' => $payment->getId(),
|
||||
'amount' => $payment->getAmount(),
|
||||
'gateway' => $this->gateway->getName(),
|
||||
]);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Mit Background Jobs
|
||||
|
||||
```php
|
||||
class EmailJob
|
||||
{
|
||||
public function handle(): void
|
||||
{
|
||||
try {
|
||||
$this->sendEmails();
|
||||
} catch (Throwable $e) {
|
||||
$this->reporter->reportThrowable($e, 'error', [
|
||||
'job' => 'email_sending',
|
||||
'batch_size' => count($this->emails),
|
||||
]);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
92
backups/docs-backup-20250731125004/framework/http/README.md
Normal file
92
backups/docs-backup-20250731125004/framework/http/README.md
Normal file
@@ -0,0 +1,92 @@
|
||||
# HTTP-Modul Dokumentation
|
||||
|
||||
## Übersicht
|
||||
|
||||
Das HTTP-Modul stellt Komponenten für die Verarbeitung von HTTP-Anfragen und -Antworten bereit.
|
||||
|
||||
## Hauptkomponenten
|
||||
|
||||
### Request
|
||||
|
||||
Repräsentiert eine HTTP-Anfrage mit Methoden zum Zugriff auf:
|
||||
- HTTP-Methode (`getMethod()`)
|
||||
- Pfad (`getPath()`)
|
||||
- Query-Parameter (`getQueryParams()`)
|
||||
- Request-Body
|
||||
- Headers
|
||||
|
||||
### Response
|
||||
|
||||
Repräsentiert eine HTTP-Antwort mit:
|
||||
- Status-Code (`getStatusCode()`)
|
||||
- Headers
|
||||
- Body
|
||||
|
||||
### Middleware
|
||||
|
||||
Ein Interface für HTTP-Middleware-Komponenten, die die Request-Verarbeitung verändern können:
|
||||
|
||||
```php
|
||||
interface Middleware
|
||||
{
|
||||
public function process(Request $request, callable $next): Response;
|
||||
}
|
||||
```
|
||||
|
||||
**Beispiel-Middleware:**
|
||||
```php
|
||||
class AnalyticsMiddleware implements Middleware
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Analytics $analytics
|
||||
) {}
|
||||
|
||||
public function process(Request $request, callable $next): Response
|
||||
{
|
||||
// Request tracken
|
||||
$this->analytics->track('http_request', [
|
||||
'method' => $request->getMethod(),
|
||||
'path' => $request->getPath(),
|
||||
]);
|
||||
|
||||
// Request weiterleiten
|
||||
$response = $next($request);
|
||||
|
||||
// Response tracken
|
||||
$this->analytics->track('http_response', [
|
||||
'status_code' => $response->getStatusCode(),
|
||||
]);
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Integration mit anderen Modulen
|
||||
|
||||
- **Router**: Routing von HTTP-Requests zu Controllers
|
||||
- **Analytics**: Tracking von HTTP-Requests und -Responses
|
||||
- **Validation**: Validierung von Request-Daten
|
||||
|
||||
## Middlewares registrieren
|
||||
|
||||
In der Anwendungsklasse:
|
||||
|
||||
```php
|
||||
$this->addMiddleware(LoggingMiddleware::class);
|
||||
$this->addMiddleware(AnalyticsMiddleware::class);
|
||||
$this->addMiddleware(AuthenticationMiddleware::class);
|
||||
```
|
||||
|
||||
## Responses erzeugen
|
||||
|
||||
```php
|
||||
// JSON-Response
|
||||
return new JsonResponse(['success' => true]);
|
||||
|
||||
// HTML-Response
|
||||
return new HtmlResponse('<html><body>Hello World</body></html>');
|
||||
|
||||
// Redirect
|
||||
return new RedirectResponse('/dashboard');
|
||||
```
|
||||
42
backups/docs-backup-20250731125004/framework/index.md
Normal file
42
backups/docs-backup-20250731125004/framework/index.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# Framework-Dokumentation
|
||||
|
||||
## Übersicht
|
||||
|
||||
Diese Dokumentation beschreibt die Architektur, Komponenten und Verwendung des Framework-Kerns des Projekts.
|
||||
|
||||
## Hauptmodule
|
||||
|
||||
- [Analytics](/framework/analytics/README.md) - System zur Erfassung und Analyse von Anwendungsdaten
|
||||
- [Core](/framework/core/README.md) - Kernkomponenten und Event-System
|
||||
- [DI (Dependency Injection)](/framework/di/README.md) - Container und Service-Management
|
||||
- [HTTP](/framework/http/README.md) - HTTP-Request/Response-Handling
|
||||
|
||||
## Richtlinien und Muster
|
||||
|
||||
- [Modul-Checkliste](/framework/MODUL-CHECKLISTE.md) - Leitfaden für die Erstellung neuer Module
|
||||
- [Erweiterungsmuster](/framework/ERWEITERUNGSPATTERN.md) - Muster zur Erweiterung des Frameworks
|
||||
|
||||
## Modulare Architektur
|
||||
|
||||
Das Framework ist modular aufgebaut, mit klaren Verantwortlichkeiten für jedes Modul. Module kommunizieren über klar definierte Interfaces und den Event-Dispatcher.
|
||||
|
||||
### Neues Modul erstellen
|
||||
|
||||
Um ein neues Modul zu erstellen, folgen Sie der [Modul-Checkliste](/framework/MODUL-CHECKLISTE.md) und beachten Sie die folgenden Kernprinzipien:
|
||||
|
||||
1. Klare Verantwortlichkeiten definieren
|
||||
2. Dependency Injection verwenden
|
||||
3. Interface-basiertes Design umsetzen
|
||||
4. Event-basierte Kommunikation nutzen
|
||||
5. Externe Abhängigkeiten minimieren
|
||||
|
||||
### Framework erweitern
|
||||
|
||||
Es gibt verschiedene Möglichkeiten, das Framework zu erweitern:
|
||||
|
||||
1. **Middleware**: HTTP-Request-Pipeline erweitern
|
||||
2. **Event-Listener**: Auf System-Events reagieren
|
||||
3. **Service-Provider**: Eigene Services registrieren
|
||||
4. **Plugin-System**: Umfangreichere Erweiterungen implementieren
|
||||
|
||||
Weitere Details finden Sie im Dokument [Erweiterungsmuster](/framework/ERWEITERUNGSPATTERN.md).
|
||||
@@ -0,0 +1,350 @@
|
||||
# Framework Performance
|
||||
|
||||
> Performance optimization features and monitoring built into the PHP framework.
|
||||
|
||||
## 🔧 Built-in Performance Features
|
||||
|
||||
### Connection Pooling
|
||||
|
||||
The framework includes advanced database connection pooling with health monitoring:
|
||||
|
||||
```php
|
||||
// Automatic connection pooling
|
||||
$pool = new ConnectionPool([
|
||||
'min_connections' => 5,
|
||||
'max_connections' => 20,
|
||||
'idle_timeout' => 300,
|
||||
'health_check_interval' => 60
|
||||
]);
|
||||
|
||||
// Health monitoring
|
||||
$healthChecker = new ConnectionHealthChecker($pool);
|
||||
$healthStatus = $healthChecker->checkHealth();
|
||||
```
|
||||
|
||||
### Query Optimization
|
||||
|
||||
#### N+1 Query Prevention
|
||||
The framework automatically detects and eliminates N+1 queries:
|
||||
|
||||
```php
|
||||
// Automatic eager loading detection
|
||||
$users = $userRepository->findWithRelations(['posts', 'comments']);
|
||||
|
||||
// Batch loading for performance
|
||||
$posts = $postRepository->loadBatch($userIds);
|
||||
```
|
||||
|
||||
#### Query Caching
|
||||
Built-in query result caching with intelligent invalidation:
|
||||
|
||||
```php
|
||||
// Cache configuration
|
||||
$cacheConfig = [
|
||||
'default_ttl' => 3600,
|
||||
'strategy' => 'write-through',
|
||||
'invalidation' => 'tag-based'
|
||||
];
|
||||
|
||||
// Automatic query caching
|
||||
$result = $repository->findCached('user-posts-' . $userId);
|
||||
```
|
||||
|
||||
### View System Performance
|
||||
|
||||
#### Template Compilation
|
||||
PHP templates are compiled and cached for optimal performance:
|
||||
|
||||
```php
|
||||
// Template compilation
|
||||
$viewProcessor = new ViewProcessor([
|
||||
'cache_path' => '/var/cache/views',
|
||||
'auto_reload' => false, // Production setting
|
||||
'optimize' => true
|
||||
]);
|
||||
```
|
||||
|
||||
#### Fragment Caching
|
||||
Cache expensive template fragments:
|
||||
|
||||
```html
|
||||
<!-- Fragment caching in templates -->
|
||||
<cache key="user-stats-<?= $userId ?>" ttl="3600">
|
||||
<?php foreach($stats as $stat): ?>
|
||||
<div class="stat"><?= $stat->render() ?></div>
|
||||
<?php endforeach; ?>
|
||||
</cache>
|
||||
```
|
||||
|
||||
## 📊 Performance Monitoring
|
||||
|
||||
### Analytics Integration
|
||||
|
||||
The framework includes comprehensive performance analytics:
|
||||
|
||||
```php
|
||||
// Performance monitoring
|
||||
class PerformanceMiddleware implements HttpMiddleware
|
||||
{
|
||||
public function handle(Request $request, Next $next): Response
|
||||
{
|
||||
$startTime = microtime(true);
|
||||
$startMemory = memory_get_usage();
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
$this->recordMetrics([
|
||||
'duration' => microtime(true) - $startTime,
|
||||
'memory' => memory_get_usage() - $startMemory,
|
||||
'route' => $request->getRoute(),
|
||||
'status' => $response->getStatusCode()
|
||||
]);
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Database Performance Tracking
|
||||
|
||||
Monitor database query performance automatically:
|
||||
|
||||
```php
|
||||
// Query performance logging
|
||||
class QueryLogger implements QueryMiddleware
|
||||
{
|
||||
public function beforeQuery(string $sql, array $params): void
|
||||
{
|
||||
$this->startTime = microtime(true);
|
||||
}
|
||||
|
||||
public function afterQuery(string $sql, array $params): void
|
||||
{
|
||||
$duration = microtime(true) - $this->startTime;
|
||||
|
||||
if ($duration > 0.1) { // Log slow queries
|
||||
$this->logger->warning('Slow query detected', [
|
||||
'sql' => $sql,
|
||||
'duration' => $duration,
|
||||
'params' => $params
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🚀 Optimization Strategies
|
||||
|
||||
### HTTP Layer Optimizations
|
||||
|
||||
#### Response Compression
|
||||
Automatic response compression based on content type:
|
||||
|
||||
```php
|
||||
// Compression middleware
|
||||
class CompressionMiddleware implements HttpMiddleware
|
||||
{
|
||||
public function handle(Request $request, Next $next): Response
|
||||
{
|
||||
$response = $next($request);
|
||||
|
||||
if ($this->shouldCompress($response)) {
|
||||
return $this->compress($response);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### HTTP Caching
|
||||
Intelligent HTTP caching with ETag support:
|
||||
|
||||
```php
|
||||
// Cache headers
|
||||
$response->headers->set('Cache-Control', 'public, max-age=3600');
|
||||
$response->headers->set('ETag', hash('sha256', $content));
|
||||
|
||||
// Conditional requests
|
||||
if ($request->headers->get('If-None-Match') === $etag) {
|
||||
return new Response('', 304);
|
||||
}
|
||||
```
|
||||
|
||||
### Asset Optimization
|
||||
|
||||
#### Static File Serving
|
||||
Optimized static file serving with proper headers:
|
||||
|
||||
```nginx
|
||||
# Nginx configuration for static assets
|
||||
location /assets/ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
add_header Vary "Accept-Encoding";
|
||||
|
||||
gzip_static on;
|
||||
brotli_static on;
|
||||
}
|
||||
```
|
||||
|
||||
#### Asset Bundling
|
||||
Framework integration with Vite for optimal asset bundling:
|
||||
|
||||
```php
|
||||
// Asset helper
|
||||
class AssetHelper
|
||||
{
|
||||
public function getAssetUrl(string $asset): string
|
||||
{
|
||||
$manifest = $this->loadManifest();
|
||||
return $manifest[$asset]['url'] ?? $asset;
|
||||
}
|
||||
|
||||
public function getCriticalCss(): string
|
||||
{
|
||||
return $this->inlineAsset('critical.css');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🔍 Performance Profiling
|
||||
|
||||
### Built-in Profiler
|
||||
|
||||
Enable the framework profiler for detailed performance analysis:
|
||||
|
||||
```php
|
||||
// Profiler configuration
|
||||
$profiler = new FrameworkProfiler([
|
||||
'enabled' => $this->isDebugMode(),
|
||||
'storage' => 'file', // or 'redis'
|
||||
'threshold' => 100, // ms
|
||||
'collect' => [
|
||||
'queries',
|
||||
'views',
|
||||
'cache',
|
||||
'events'
|
||||
]
|
||||
]);
|
||||
```
|
||||
|
||||
### Memory Usage Tracking
|
||||
|
||||
Monitor memory usage throughout the request lifecycle:
|
||||
|
||||
```php
|
||||
// Memory tracking
|
||||
class MemoryTracker
|
||||
{
|
||||
public function trackOperation(string $operation, callable $callback)
|
||||
{
|
||||
$beforeMemory = memory_get_usage(true);
|
||||
$beforePeak = memory_get_peak_usage(true);
|
||||
|
||||
$result = $callback();
|
||||
|
||||
$afterMemory = memory_get_usage(true);
|
||||
$afterPeak = memory_get_peak_usage(true);
|
||||
|
||||
$this->recordMemoryUsage([
|
||||
'operation' => $operation,
|
||||
'memory_used' => $afterMemory - $beforeMemory,
|
||||
'peak_increase' => $afterPeak - $beforePeak
|
||||
]);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ⚡ Performance Best Practices
|
||||
|
||||
### Database Best Practices
|
||||
|
||||
1. **Use Indexes**: Ensure proper database indexing
|
||||
2. **Lazy Loading**: Load data only when needed
|
||||
3. **Batch Operations**: Group database operations
|
||||
4. **Connection Reuse**: Leverage connection pooling
|
||||
|
||||
```php
|
||||
// Efficient database operations
|
||||
class UserService
|
||||
{
|
||||
public function getUsersWithPosts(array $userIds): array
|
||||
{
|
||||
// Single query with join instead of N+1
|
||||
return $this->repository->findUsersWithPosts($userIds);
|
||||
}
|
||||
|
||||
public function batchUpdateUsers(array $updates): void
|
||||
{
|
||||
// Batch update instead of individual queries
|
||||
$this->repository->batchUpdate($updates);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### View Optimization
|
||||
|
||||
1. **Template Caching**: Cache compiled templates
|
||||
2. **Fragment Caching**: Cache expensive view fragments
|
||||
3. **Lazy Loading**: Load view components on demand
|
||||
4. **Asset Optimization**: Minify and compress assets
|
||||
|
||||
```php
|
||||
// Optimized view rendering
|
||||
class OptimizedViewController
|
||||
{
|
||||
public function render(string $template, array $data): Response
|
||||
{
|
||||
// Use cached template if available
|
||||
$compiled = $this->templateCache->get($template);
|
||||
|
||||
if (!$compiled) {
|
||||
$compiled = $this->compiler->compile($template);
|
||||
$this->templateCache->set($template, $compiled);
|
||||
}
|
||||
|
||||
return $this->renderCompiled($compiled, $data);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 📈 Monitoring & Alerts
|
||||
|
||||
### Performance Metrics Collection
|
||||
|
||||
Collect and analyze key performance metrics:
|
||||
|
||||
```php
|
||||
// Metrics collection
|
||||
$metrics = [
|
||||
'response_time' => $responseTime,
|
||||
'memory_usage' => memory_get_peak_usage(true),
|
||||
'database_queries' => $queryCount,
|
||||
'cache_hits' => $cacheHits,
|
||||
'cache_misses' => $cacheMisses
|
||||
];
|
||||
|
||||
$this->metricsCollector->record($metrics);
|
||||
```
|
||||
|
||||
### Alert Configuration
|
||||
|
||||
Set up alerts for performance degradation:
|
||||
|
||||
```php
|
||||
// Performance alerts
|
||||
$alertConfig = [
|
||||
'response_time_threshold' => 1000, // ms
|
||||
'memory_threshold' => 128 * 1024 * 1024, // 128MB
|
||||
'query_count_threshold' => 50,
|
||||
'error_rate_threshold' => 0.01 // 1%
|
||||
];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
*For general performance guidelines, see [Performance Guidelines](../../development/performance.md)*
|
||||
*For analytics configuration, see [Analytics System](../analytics/README.md)*
|
||||
359
backups/docs-backup-20250731125004/framework/views/overview.md
Normal file
359
backups/docs-backup-20250731125004/framework/views/overview.md
Normal file
@@ -0,0 +1,359 @@
|
||||
# View System Overview
|
||||
|
||||
> Advanced template processing system with DOM manipulation, component architecture, and intelligent caching.
|
||||
|
||||
## 🏗 Architecture
|
||||
|
||||
The view system is built around **DOM-based processing** using PHP 8.4's native HTML5 parser, enabling sophisticated template manipulation while maintaining performance through intelligent caching.
|
||||
|
||||
### Core Components
|
||||
|
||||
```
|
||||
src/Framework/View/
|
||||
├── Engine.php # Main template engine
|
||||
├── TemplateRenderer.php # Rendering coordinator
|
||||
├── DomProcessor.php # DOM manipulation interface
|
||||
├── RenderContext.php # Template context data
|
||||
├── ComponentRenderer.php # Component system
|
||||
├── Processors/ # Template processors
|
||||
├── Caching/ # Multi-level caching
|
||||
└── Loading/ # Template resolution
|
||||
```
|
||||
|
||||
## 📝 Basic Usage
|
||||
|
||||
### Simple Template Rendering
|
||||
|
||||
```php
|
||||
// Controller
|
||||
class HomeController
|
||||
{
|
||||
public function index(TemplateRenderer $renderer): ViewResult
|
||||
{
|
||||
return new ViewResult('home', [
|
||||
'title' => 'Welcome',
|
||||
'user' => $user,
|
||||
'stats' => $this->getStats()
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Template Structure
|
||||
|
||||
```html
|
||||
<!-- templates/home.view.php -->
|
||||
<layout name="main">
|
||||
<slot name="title">{title}</slot>
|
||||
<slot name="content">
|
||||
<div class="welcome">
|
||||
<h1>Hello, {user.name}!</h1>
|
||||
<div class="stats">
|
||||
<for data="stats" as="stat">
|
||||
<div class="stat-item">
|
||||
<span class="value">{stat.value}</span>
|
||||
<span class="label">{stat.label}</span>
|
||||
</div>
|
||||
</for>
|
||||
</div>
|
||||
</div>
|
||||
</slot>
|
||||
</layout>
|
||||
```
|
||||
|
||||
## 🧩 Component System
|
||||
|
||||
### Component Definition
|
||||
|
||||
```html
|
||||
<!-- components/card.view.php -->
|
||||
<div class="card {classes}">
|
||||
<if condition="title">
|
||||
<header class="card-header">
|
||||
<h3>{title}</h3>
|
||||
</header>
|
||||
</if>
|
||||
|
||||
<div class="card-body">
|
||||
<slot name="content">{content}</slot>
|
||||
</div>
|
||||
|
||||
<if condition="actions">
|
||||
<footer class="card-footer">
|
||||
<slot name="actions"></slot>
|
||||
</footer>
|
||||
</if>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Component Usage
|
||||
|
||||
```html
|
||||
<component name="card" title="User Profile" classes="profile-card">
|
||||
<slot name="content">
|
||||
<p>User: {user.name}</p>
|
||||
<p>Email: {user.email}</p>
|
||||
</slot>
|
||||
|
||||
<slot name="actions">
|
||||
<button>Edit Profile</button>
|
||||
<button>View History</button>
|
||||
</slot>
|
||||
</component>
|
||||
```
|
||||
|
||||
## 🔄 Template Processors
|
||||
|
||||
### Available Processors
|
||||
|
||||
| Processor | Purpose | Documentation |
|
||||
|-----------|---------|---------------|
|
||||
| **LayoutTagProcessor** | Layout system implementation | [Details](processors.md#layout) |
|
||||
| **ComponentProcessor** | Reusable UI components | [Details](processors.md#components) |
|
||||
| **SlotProcessor** | Content injection system | [Details](processors.md#slots) |
|
||||
| **IfProcessor** | Conditional rendering | [Details](processors.md#conditionals) |
|
||||
| **ForProcessor** | Loop iteration | [Details](processors.md#loops) |
|
||||
| **PlaceholderReplacer** | Variable substitution | [Details](processors.md#placeholders) |
|
||||
| **AssetInjector** | JS/CSS asset injection | [Details](processors.md#assets) |
|
||||
| **MetaManipulator** | Meta tag extraction | [Details](processors.md#meta) |
|
||||
|
||||
### Processing Pipeline
|
||||
|
||||
```
|
||||
1. Structure Processors
|
||||
├── LayoutTagProcessor # Apply layouts
|
||||
└── IncludeProcessor # Include external files
|
||||
|
||||
2. Component Processors
|
||||
├── ComponentProcessor # Process components
|
||||
└── SlotProcessor # Handle slots
|
||||
|
||||
3. Logic Processors
|
||||
├── IfProcessor # Conditional logic
|
||||
├── ForProcessor # Loops
|
||||
└── SwitchCaseProcessor # Switch statements
|
||||
|
||||
4. Content Processors
|
||||
├── PlaceholderReplacer # Variable substitution
|
||||
├── DateFormatProcessor # Date formatting
|
||||
└── MetaManipulator # Meta extraction
|
||||
|
||||
5. Asset Processors
|
||||
└── AssetInjector # CSS/JS injection
|
||||
|
||||
6. Optimization Processors
|
||||
├── CommentStripProcessor # Remove comments
|
||||
├── RemoveEmptyLinesProcessor
|
||||
└── VoidElementsSelfClosingProcessor
|
||||
```
|
||||
|
||||
## 🎯 Advanced Features
|
||||
|
||||
### Conditional Rendering
|
||||
|
||||
```html
|
||||
<!-- Simple conditions -->
|
||||
<if condition="user.isAdmin">
|
||||
<admin-panel></admin-panel>
|
||||
</if>
|
||||
|
||||
<!-- Complex conditions -->
|
||||
<if condition="user.role === 'admin' && features.adminPanel">
|
||||
<component name="admin-dashboard"></component>
|
||||
</if>
|
||||
|
||||
<!-- If-else chains -->
|
||||
<if condition="user.isAdmin">
|
||||
<admin-view></admin-view>
|
||||
<else-if condition="user.isModerator">
|
||||
<moderator-view></moderator-view>
|
||||
<else>
|
||||
<user-view></user-view>
|
||||
</if>
|
||||
```
|
||||
|
||||
### Loop Iteration
|
||||
|
||||
```html
|
||||
<!-- Simple loops -->
|
||||
<for data="users" as="user">
|
||||
<div class="user-card">
|
||||
<h3>{user.name}</h3>
|
||||
<p>{user.email}</p>
|
||||
</div>
|
||||
</for>
|
||||
|
||||
<!-- Loops with keys -->
|
||||
<for data="categories" as="category" key="categoryId">
|
||||
<section data-category="{categoryId}">
|
||||
<h2>{category.name}</h2>
|
||||
<for data="category.items" as="item">
|
||||
<article>{item.title}</article>
|
||||
</for>
|
||||
</section>
|
||||
</for>
|
||||
|
||||
<!-- Loops with index -->
|
||||
<for data="items" as="item" index="i">
|
||||
<div class="item-{i}">
|
||||
Position: {i + 1} - {item.name}
|
||||
</div>
|
||||
</for>
|
||||
```
|
||||
|
||||
### Layout System
|
||||
|
||||
```html
|
||||
<!-- Layout definition: layouts/main.view.php -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title><slot name="title">Default Title</slot></title>
|
||||
<meta name="description" content="<slot name="description"></slot>">
|
||||
<slot name="head"></slot>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<nav><!-- Navigation --></nav>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<slot name="content"></slot>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<slot name="footer">© 2024 Framework</slot>
|
||||
</footer>
|
||||
|
||||
<slot name="scripts"></slot>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## 💾 Caching System
|
||||
|
||||
### Cache Strategies
|
||||
|
||||
```php
|
||||
// Automatic caching based on template analysis
|
||||
$cacheStrategy = $analyzer->determineCacheStrategy($template);
|
||||
|
||||
// Manual cache control
|
||||
$context = new RenderContext($data);
|
||||
$context->setCacheStrategy(CacheStrategy::FULL_PAGE);
|
||||
$context->setCacheTags(['user:123', 'posts']);
|
||||
$context->setCacheTtl(3600);
|
||||
```
|
||||
|
||||
### Cache Invalidation
|
||||
|
||||
```php
|
||||
// Tag-based invalidation
|
||||
$cache->invalidateByTags(['user:123']);
|
||||
|
||||
// Template-based invalidation
|
||||
$cache->invalidateTemplate('user-profile');
|
||||
|
||||
// Smart invalidation on data changes
|
||||
$user->save(); // Automatically invalidates user-related caches
|
||||
```
|
||||
|
||||
## 🔧 Template Functions
|
||||
|
||||
### Built-in Functions
|
||||
|
||||
```html
|
||||
<!-- URL generation -->
|
||||
<a href="{url('user.profile', {id: user.id})}">Profile</a>
|
||||
|
||||
<!-- Image slots with responsive images -->
|
||||
<img src="{imageSlot('hero', 'medium')}"
|
||||
srcset="{imageSlot('hero', 'small')} 480w,
|
||||
{imageSlot('hero', 'medium')} 768w,
|
||||
{imageSlot('hero', 'large')} 1200w">
|
||||
|
||||
<!-- Date formatting -->
|
||||
<time datetime="{user.createdAt|iso8601}">
|
||||
{user.createdAt|date('d.m.Y H:i')}
|
||||
</time>
|
||||
|
||||
<!-- Asset URLs -->
|
||||
<link rel="stylesheet" href="{asset('css/app.css')}">
|
||||
<script src="{asset('js/app.js')}" defer></script>
|
||||
```
|
||||
|
||||
### Custom Functions
|
||||
|
||||
```php
|
||||
// Register custom function
|
||||
$templateEngine->registerFunction('currency', function ($amount, $currency = 'EUR') {
|
||||
return number_format($amount, 2, ',', '.') . ' ' . $currency;
|
||||
});
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- Use custom function -->
|
||||
<span class="price">{product.price|currency('USD')}</span>
|
||||
```
|
||||
|
||||
## 🎨 Integration with CSS/JS
|
||||
|
||||
### Asset Management
|
||||
|
||||
```html
|
||||
<!-- Vite asset injection -->
|
||||
<head>
|
||||
{vite('resources/css/app.css')}
|
||||
{vite('resources/js/app.js')}
|
||||
</head>
|
||||
|
||||
<!-- Conditional assets -->
|
||||
<if condition="isDevelopment">
|
||||
<script src="http://localhost:3000/@vite/client" type="module"></script>
|
||||
</if>
|
||||
```
|
||||
|
||||
### Component-specific Assets
|
||||
|
||||
```html
|
||||
<!-- components/chart.view.php -->
|
||||
<div class="chart-container" data-chart="{chartData}">
|
||||
<slot name="head">
|
||||
<link rel="stylesheet" href="{asset('css/charts.css')}">
|
||||
</slot>
|
||||
|
||||
<slot name="scripts">
|
||||
<script src="{asset('js/charts.js')}" defer></script>
|
||||
</slot>
|
||||
</div>
|
||||
```
|
||||
|
||||
## 🔍 Debugging & Development
|
||||
|
||||
### Template Debugging
|
||||
|
||||
```html
|
||||
<!-- Debug mode shows processing steps -->
|
||||
<debug>
|
||||
Template: {template.name}
|
||||
Context: {context.data|json}
|
||||
Cache: {cache.status}
|
||||
</debug>
|
||||
```
|
||||
|
||||
### Performance Analysis
|
||||
|
||||
```php
|
||||
// Template performance metrics
|
||||
$metrics = $templateEngine->getMetrics();
|
||||
echo "Render time: {$metrics->renderTime}ms\n";
|
||||
echo "Cache hits: {$metrics->cacheHits}\n";
|
||||
echo "Processors: {$metrics->processorsRun}\n";
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
*For detailed processor documentation, see [Template Processors](processors.md)*
|
||||
*For component examples, see [Component Library](../design-system/components.md)*
|
||||
*For caching strategies, see [View Caching](caching.md)*
|
||||
Reference in New Issue
Block a user