singleton(Logger::class, $logger); // 2. Initialize ML Engine echo "Step 1: Initializing ML Engine...\n"; $mlEngineInitializer = new NPlusOneDetectionEngineInitializer($environment, $clock, $logger); $mlEngine = $mlEngineInitializer(); $container->singleton(NPlusOneDetectionEngine::class, $mlEngine); echo "✓ ML Engine initialized\n"; echo " Configuration: " . json_encode($mlEngine->getConfiguration(), JSON_PRETTY_PRINT) . "\n\n"; // 3. Create QueryLogger and simulate query execution echo "Step 2: Simulating Query Execution...\n"; $queryLogger = new QueryLogger(); $queryLogger->enable(); // Simulate N+1 scenario: 1 query + 10 repeated queries echo "Logging initial query: SELECT * FROM users\n"; $queryLogger->logQuery( 'SELECT * FROM users', [], 10.5, 10 ); echo "Logging N+1 pattern: 10 repeated queries in loop\n"; for ($i = 1; $i <= 10; $i++) { $queryLogger->logQuery( "SELECT * FROM posts WHERE user_id = $i", [$i], 5.0 + ($i * 0.2), rand(5, 15) ); } $queryLogger->disable(); echo "✓ Query logging completed\n"; echo " Total queries logged: " . $queryLogger->getQueryCount() . "\n"; echo " Total execution time: " . round($queryLogger->getTotalExecutionTime(), 2) . "ms\n\n"; // 4. Create NPlusOneDetectionService with ML Integration echo "Step 3: Creating N+1 Detection Service with ML...\n"; $detector = new NPlusOneDetector( minExecutionCount: 5, minSeverityScore: 4.0 ); $eagerLoadingAnalyzer = new EagerLoadingAnalyzer(); $detectionService = new NPlusOneDetectionService( queryLogger: $queryLogger, detector: $detector, eagerLoadingAnalyzer: $eagerLoadingAnalyzer, logger: $logger, mlEngine: $mlEngine ); echo "✓ Detection service initialized\n"; echo " ML engine enabled: " . ($mlEngine->isEnabled() ? 'Yes' : 'No') . "\n\n"; // 5. Perform Analysis echo "Step 4: Analyzing Queries...\n"; echo "=====================================\n\n"; $analysisResult = $detectionService->analyze(); // 6. Display Traditional Pattern-Based Results echo "=== Traditional Pattern Detection ===\n"; $stats = $analysisResult['statistics']; echo "Query Statistics:\n"; echo " Total queries: " . $stats['total_queries'] . "\n"; echo " Total patterns: " . $stats['total_patterns'] . "\n"; echo " N+1 patterns detected: " . $stats['n_plus_one_patterns'] . "\n"; echo " N+1 queries: " . $stats['n_plus_one_queries'] . " (" . round($stats['n_plus_one_percentage'], 1) . "% of total)\n"; echo " Time wasted: " . round($stats['n_plus_one_time_ms'], 2) . "ms (" . round($stats['time_wasted_percentage'], 1) . "% of total)\n\n"; if (!empty($analysisResult['detections'])) { echo "Detected N+1 Issues:\n"; foreach ($analysisResult['detections'] as $index => $detection) { echo " [" . ($index + 1) . "] {$detection->getSeverityLevel()} - {$detection->pattern->getTableName()}\n"; echo " Executions: {$detection->pattern->getExecutionCount()}\n"; echo " Total time: " . round($detection->pattern->getTotalExecutionTimeMs(), 2) . "ms\n"; echo " Impact: {$detection->getPerformanceImpact()}\n"; } echo "\n"; } // 7. Display ML Analysis Results if (isset($analysisResult['ml_analysis'])) { echo "=== Machine Learning Analysis ===\n"; $mlAnalysis = $analysisResult['ml_analysis']; echo "ML Analysis Status: " . ($mlAnalysis['success'] ? '✓ Success' : '✗ Failed') . "\n"; if ($mlAnalysis['success']) { echo "Anomalies Detected: " . $mlAnalysis['anomalies_count'] . "\n"; echo "Overall Confidence: " . round($mlAnalysis['overall_confidence'], 2) . "%\n"; echo "Analysis Time: " . round($mlAnalysis['analysis_time_ms'], 2) . "ms\n\n"; if (!empty($mlAnalysis['anomalies'])) { echo "ML-Detected Anomalies:\n"; foreach ($mlAnalysis['anomalies'] as $index => $anomaly) { echo " [" . ($index + 1) . "] {$anomaly->type->value}\n"; echo " Confidence: " . round($anomaly->confidence->value, 2) . "%\n"; echo " Severity: {$anomaly->severity->value}\n"; echo " Description: {$anomaly->description}\n"; if (!empty($anomaly->context)) { echo " Context: " . json_encode($anomaly->context) . "\n"; } echo "\n"; } } echo "Extracted Features (Sample):\n"; $sampleFeatures = array_slice($mlAnalysis['features'], 0, 5); foreach ($sampleFeatures as $feature) { echo " - {$feature->name}: " . round($feature->value, 4) . " {$feature->unit}\n"; } echo "\n"; } else { echo "Error: " . ($mlAnalysis['error'] ?? 'Unknown error') . "\n\n"; } } else { echo "=== Machine Learning Analysis ===\n"; echo "ML engine not enabled or not available\n\n"; } // 8. Generate Eager Loading Strategies if (!empty($analysisResult['strategies'])) { echo "=== Optimization Strategies ===\n"; foreach ($analysisResult['strategies'] as $strategy) { echo "Strategy for {$strategy->entityClass}:\n"; echo " Relations to eager load: " . implode(', ', $strategy->relationsToLoad) . "\n"; echo " Expected improvement: " . $strategy->expectedImprovement . "%\n"; echo " Implementation: {$strategy->implementationHint}\n\n"; } } // 9. Summary echo "=== Integration Summary ===\n"; echo "✓ Traditional pattern detection completed\n"; echo "✓ ML-based anomaly detection completed\n"; echo "✓ Combined analysis provides:\n"; echo " - Pattern-based detection (existing framework)\n"; echo " - ML-based anomaly detection (new capability)\n"; echo " - Eager loading optimization strategies\n"; echo " - Comprehensive performance insights\n\n"; echo "Integration Benefits:\n"; echo "1. Enhanced detection accuracy through ML\n"; echo "2. Reduced false positives via confidence scoring\n"; echo "3. Automatic feature extraction from query patterns\n"; echo "4. Real-time anomaly detection with low overhead\n"; echo "5. Seamless integration with existing detection pipeline\n\n"; echo "✓ N+1 Detection ML Integration Example Complete\n";