feat: optimize OPcache preload script for memory efficiency and improved performance

This commit is contained in:
2025-12-21 08:03:09 -05:00
parent f77a1d4e5d
commit 4b6fbea45d

View File

@@ -1,743 +1,295 @@
<?php <?php
/** /**
* High-Performance OPcache Preload Script for PHP 8.3-FPM * OPcache Preload Script for PHP 8.3-FPM
* Optimized for Paymenter/VirtNet with Laravel 12, Filament 3, Livewire 3, Octane * Optimized for Paymenter/VirtNet - Memory-efficient version
* *
* Configure in php.ini or www.conf: * Configure in php.ini:
* opcache.preload=/var/www/html/preload.php * opcache.preload=/var/www/paymenter/preload.php
* opcache.preload_user=www-data * opcache.preload_user=www-data
* opcache.memory_consumption=512 * opcache.memory_consumption=256
* opcache.interned_strings_buffer=128 * opcache.interned_strings_buffer=64
* opcache.max_accelerated_files=50000 * opcache.max_accelerated_files=30000
* opcache.validate_timestamps=0 * opcache.validate_timestamps=0
* opcache.save_comments=1 * opcache.save_comments=1
* opcache.enable_file_override=1
* opcache.jit=1255 * opcache.jit=1255
* opcache.jit_buffer_size=256M * opcache.jit_buffer_size=128M
* opcache.jit_hot_func=127
* opcache.jit_hot_loop=127
* opcache.jit_hot_return=8
* opcache.jit_hot_side_exit=8
*
* After deployment run:
* php artisan optimize
* php artisan filament:optimize
* php artisan view:cache
* php artisan event:cache
* php artisan icons:cache
* sudo systemctl reload php8.3-fpm
*/ */
declare(strict_types=1); declare(strict_types=1);
// Ensure OPcache is available
if (!function_exists('opcache_compile_file')) { if (!function_exists('opcache_compile_file')) {
die('OPcache extension is not loaded'); return;
} }
$basePath = __DIR__; $basePath = __DIR__;
$count = 0;
// Performance tracking
$stats = [
'preloaded' => 0,
'skipped' => 0,
'errors' => [],
'start_time' => hrtime(true),
'start_memory' => memory_get_usage(true),
];
// =============================================================================
// PRELOAD FUNCTIONS
// =============================================================================
/** /**
* Compile a single file into OPcache * Safely compile a file into OPcache
* Returns true if successfully compiled
*/ */
function preloadFile(string $path): bool function preload(string $path): bool
{ {
global $stats; global $count;
// Fast path checks
if (!is_file($path) || !is_readable($path)) { if (!is_file($path) || !is_readable($path)) {
return false; return false;
} }
// Skip empty files
if (filesize($path) === 0) {
return false;
}
try { try {
if (@opcache_compile_file($path)) { if (@opcache_compile_file($path)) {
$stats['preloaded']++; $count++;
return true; return true;
} }
} catch (Throwable $e) { } catch (Throwable $e) {
$stats['errors'][] = basename($path) . ': ' . $e->getMessage(); // Skip files with errors
} }
$stats['skipped']++;
return false; return false;
} }
/** /**
* Preload files from array with existence check * Preload a directory (non-recursive for control)
*/ */
function preloadFiles(array $files): void function preloadDir(string $dir): void
{ {
foreach ($files as $file) { if (!is_dir($dir)) {
preloadFile($file); return;
}
foreach (glob($dir . '/*.php') as $file) {
preload($file);
} }
} }
/** /**
* Recursively preload directory with filtering * Preload a directory recursively
*/ */
function preloadDirectory(string $dir, array $excludePatterns = [], int $maxDepth = 20): void function preloadDirRecursive(string $dir, int $maxDepth = 10): void
{ {
if (!is_dir($dir) || !is_readable($dir)) { if (!is_dir($dir) || $maxDepth < 0) {
return; return;
} }
$iterator = new RecursiveIteratorIterator( foreach (glob($dir . '/*.php') as $file) {
new RecursiveDirectoryIterator( preload($file);
$dir, }
FilesystemIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS
), foreach (glob($dir . '/*', GLOB_ONLYDIR) as $subdir) {
RecursiveIteratorIterator::LEAVES_ONLY $basename = basename($subdir);
); // Skip test/dev directories
$iterator->setMaxDepth($maxDepth); if (in_array(strtolower($basename), ['tests', 'test', 'testing', 'stubs', 'fixtures', 'mock', 'mocks'])) {
$files = [];
foreach ($iterator as $file) {
if (!$file->isFile() || $file->getExtension() !== 'php') {
continue; continue;
} }
preloadDirRecursive($subdir, $maxDepth - 1);
$path = $file->getRealPath();
if ($path === false) {
continue;
}
// Apply exclude patterns
$skip = false;
foreach ($excludePatterns as $pattern) {
if (preg_match($pattern, $path)) {
$skip = true;
break;
}
}
if (!$skip) {
$files[] = $path;
}
}
// Sort for consistent ordering (helps with JIT optimization)
sort($files, SORT_STRING);
foreach ($files as $path) {
preloadFile($path);
} }
} }
/**
* Preload specific classes from a namespace (using Composer's classmap)
*/
function preloadClassmap(string $classmapFile): void
{
if (!is_file($classmapFile)) {
return;
}
$classmap = require $classmapFile;
if (!is_array($classmap)) {
return;
}
foreach ($classmap as $class => $file) {
preloadFile($file);
}
}
// Global exclusion patterns (tests, stubs, dev-only files)
$excludePatterns = [
'#[/\\\\][Tt]ests?[/\\\\]#',
'#[/\\\\][Ss]tubs?[/\\\\]#',
'#[/\\\\][Ff]ixtures?[/\\\\]#',
'#[/\\\\][Mm]ocks?[/\\\\]#',
'#[Tt]est\.php$#',
'#[Ss]tub\.php$#',
'#[Ss]pec\.php$#',
'#phpunit#i',
'#[/\\\\]\.#', // Hidden files/dirs
];
// ============================================================================= // =============================================================================
// PHASE 1: COMPOSER AUTOLOADER (Load First - Critical) // 1. LARAVEL CACHED FILES (Most Important)
// ============================================================================= // =============================================================================
// Autoloader must be preloaded first for class resolution $cacheFiles = [
$composerFiles = [ '/bootstrap/cache/packages.php',
$basePath . '/vendor/composer/ClassLoader.php', '/bootstrap/cache/services.php',
$basePath . '/vendor/composer/InstalledVersions.php', '/bootstrap/cache/config.php',
$basePath . '/vendor/composer/autoload_real.php', '/bootstrap/cache/routes-v7.php',
$basePath . '/vendor/composer/autoload_static.php', '/bootstrap/cache/events.php',
$basePath . '/vendor/composer/autoload_classmap.php', '/bootstrap/cache/filament.php',
$basePath . '/vendor/composer/autoload_files.php',
$basePath . '/vendor/composer/autoload_namespaces.php',
$basePath . '/vendor/composer/autoload_psr4.php',
$basePath . '/vendor/autoload.php',
]; ];
preloadFiles($composerFiles); foreach ($cacheFiles as $file) {
preload($basePath . $file);
// Preload entire Composer classmap for maximum performance
if (is_file($basePath . '/vendor/composer/autoload_classmap.php')) {
preloadClassmap($basePath . '/vendor/composer/autoload_classmap.php');
} }
// ============================================================================= // =============================================================================
// PHASE 2: LARAVEL CACHED FILES (High Priority) // 2. COMPOSER AUTOLOADER
// ============================================================================= // =============================================================================
$laravelCacheFiles = [ preload($basePath . '/vendor/composer/ClassLoader.php');
// Core cached files preload($basePath . '/vendor/composer/autoload_static.php');
$basePath . '/bootstrap/cache/packages.php',
$basePath . '/bootstrap/cache/services.php',
$basePath . '/bootstrap/cache/config.php',
$basePath . '/bootstrap/cache/routes-v7.php',
$basePath . '/bootstrap/cache/events.php',
// Filament cache
$basePath . '/bootstrap/cache/filament.php',
$basePath . '/bootstrap/cache/filament/panels.php',
// Livewire cache
$basePath . '/bootstrap/cache/livewire-components.php',
// Icons cache (Blade Icons)
$basePath . '/bootstrap/cache/blade-icons.php',
];
preloadFiles($laravelCacheFiles);
// ============================================================================= // =============================================================================
// PHASE 3: PSR INTERFACES (Required for type resolution) // 3. APPLICATION MODELS (High Priority)
// ============================================================================= // =============================================================================
$psrDirs = [ preloadDir($basePath . '/app/Models');
$basePath . '/vendor/psr/container/src',
$basePath . '/vendor/psr/http-message/src',
$basePath . '/vendor/psr/http-client/src',
$basePath . '/vendor/psr/http-factory/src',
$basePath . '/vendor/psr/log/src',
$basePath . '/vendor/psr/cache/src',
$basePath . '/vendor/psr/simple-cache/src',
$basePath . '/vendor/psr/event-dispatcher/src',
$basePath . '/vendor/psr/clock/src',
];
foreach ($psrDirs as $dir) {
preloadDirectory($dir, $excludePatterns);
}
// ============================================================================= // =============================================================================
// PHASE 4: SYMFONY COMPONENTS (Laravel's HTTP Foundation) // 4. LARAVEL CORE (Selective - Most Used Classes Only)
// =============================================================================
$symfonyComponents = [
// HTTP Foundation (most critical)
$basePath . '/vendor/symfony/http-foundation',
// HTTP Kernel
$basePath . '/vendor/symfony/http-kernel',
// Routing
$basePath . '/vendor/symfony/routing',
// Event Dispatcher
$basePath . '/vendor/symfony/event-dispatcher',
$basePath . '/vendor/symfony/event-dispatcher-contracts',
// Console (for Artisan commands)
$basePath . '/vendor/symfony/console',
// Error Handler
$basePath . '/vendor/symfony/error-handler',
// Finder
$basePath . '/vendor/symfony/finder',
// Process
$basePath . '/vendor/symfony/process',
// Service Contracts
$basePath . '/vendor/symfony/service-contracts',
// Translation
$basePath . '/vendor/symfony/translation',
$basePath . '/vendor/symfony/translation-contracts',
// Var Dumper (for debugging)
$basePath . '/vendor/symfony/var-dumper',
// Mime
$basePath . '/vendor/symfony/mime',
// Mailer
$basePath . '/vendor/symfony/mailer',
// String (Slugger, etc.)
$basePath . '/vendor/symfony/string',
// UID
$basePath . '/vendor/symfony/uid',
// Clock
$basePath . '/vendor/symfony/clock',
];
foreach ($symfonyComponents as $dir) {
preloadDirectory($dir, $excludePatterns, 10);
}
// =============================================================================
// PHASE 5: LARAVEL FRAMEWORK CORE
// ============================================================================= // =============================================================================
$laravelCore = [ $laravelCore = [
// Contracts (interfaces - load first)
$basePath . '/vendor/laravel/framework/src/Illuminate/Contracts',
// Container (DI)
$basePath . '/vendor/laravel/framework/src/Illuminate/Container',
// Foundation // Foundation
$basePath . '/vendor/laravel/framework/src/Illuminate/Foundation', '/vendor/laravel/framework/src/Illuminate/Foundation/Application.php',
'/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php',
'/vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php',
// Support (helpers, traits, collections) // Container
$basePath . '/vendor/laravel/framework/src/Illuminate/Support', '/vendor/laravel/framework/src/Illuminate/Container/Container.php',
$basePath . '/vendor/laravel/framework/src/Illuminate/Collections', '/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php',
$basePath . '/vendor/laravel/framework/src/Illuminate/Conditionable',
$basePath . '/vendor/laravel/framework/src/Illuminate/Macroable',
// HTTP Layer // HTTP
$basePath . '/vendor/laravel/framework/src/Illuminate/Http', '/vendor/laravel/framework/src/Illuminate/Http/Request.php',
$basePath . '/vendor/laravel/framework/src/Illuminate/Routing', '/vendor/laravel/framework/src/Illuminate/Http/Response.php',
$basePath . '/vendor/laravel/framework/src/Illuminate/Pipeline', '/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php',
'/vendor/laravel/framework/src/Illuminate/Http/RedirectResponse.php',
// Database & Eloquent (critical for your app) // Routing
$basePath . '/vendor/laravel/framework/src/Illuminate/Database', '/vendor/laravel/framework/src/Illuminate/Routing/Router.php',
'/vendor/laravel/framework/src/Illuminate/Routing/Route.php',
'/vendor/laravel/framework/src/Illuminate/Routing/Controller.php',
'/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php',
'/vendor/laravel/framework/src/Illuminate/Routing/Redirector.php',
// Database
'/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php',
'/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php',
'/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php',
'/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php',
'/vendor/laravel/framework/src/Illuminate/Database/Connection.php',
'/vendor/laravel/framework/src/Illuminate/Database/MySqlConnection.php',
// Support
'/vendor/laravel/framework/src/Illuminate/Support/Collection.php',
'/vendor/laravel/framework/src/Illuminate/Support/Str.php',
'/vendor/laravel/framework/src/Illuminate/Support/Arr.php',
'/vendor/laravel/framework/src/Illuminate/Support/Carbon.php',
'/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php',
// Auth // Auth
$basePath . '/vendor/laravel/framework/src/Illuminate/Auth', '/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php',
'/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php',
// Session & Cookie // Session
$basePath . '/vendor/laravel/framework/src/Illuminate/Session', '/vendor/laravel/framework/src/Illuminate/Session/SessionManager.php',
$basePath . '/vendor/laravel/framework/src/Illuminate/Cookie', '/vendor/laravel/framework/src/Illuminate/Session/Store.php',
// View
'/vendor/laravel/framework/src/Illuminate/View/Factory.php',
'/vendor/laravel/framework/src/Illuminate/View/View.php',
'/vendor/laravel/framework/src/Illuminate/View/Component.php',
// Cache // Cache
$basePath . '/vendor/laravel/framework/src/Illuminate/Cache', '/vendor/laravel/framework/src/Illuminate/Cache/CacheManager.php',
'/vendor/laravel/framework/src/Illuminate/Cache/Repository.php',
// Events '/vendor/laravel/framework/src/Illuminate/Cache/RedisStore.php',
$basePath . '/vendor/laravel/framework/src/Illuminate/Events',
// Queue
$basePath . '/vendor/laravel/framework/src/Illuminate/Queue',
// Validation // Validation
$basePath . '/vendor/laravel/framework/src/Illuminate/Validation', '/vendor/laravel/framework/src/Illuminate/Validation/Validator.php',
'/vendor/laravel/framework/src/Illuminate/Validation/Factory.php',
// Views & Blade // Pipeline
$basePath . '/vendor/laravel/framework/src/Illuminate/View', '/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php',
// Mail
$basePath . '/vendor/laravel/framework/src/Illuminate/Mail',
$basePath . '/vendor/laravel/framework/src/Illuminate/Notifications',
// Encryption & Hashing
$basePath . '/vendor/laravel/framework/src/Illuminate/Encryption',
$basePath . '/vendor/laravel/framework/src/Illuminate/Hashing',
// Filesystem
$basePath . '/vendor/laravel/framework/src/Illuminate/Filesystem',
// Console
$basePath . '/vendor/laravel/framework/src/Illuminate/Console',
// Log
$basePath . '/vendor/laravel/framework/src/Illuminate/Log',
// Config
$basePath . '/vendor/laravel/framework/src/Illuminate/Config',
// Translation
$basePath . '/vendor/laravel/framework/src/Illuminate/Translation',
// Pagination
$basePath . '/vendor/laravel/framework/src/Illuminate/Pagination',
// Bus (Commands)
$basePath . '/vendor/laravel/framework/src/Illuminate/Bus',
// Process
$basePath . '/vendor/laravel/framework/src/Illuminate/Process',
// Concurrency
$basePath . '/vendor/laravel/framework/src/Illuminate/Concurrency',
]; ];
foreach ($laravelCore as $dir) { foreach ($laravelCore as $file) {
preloadDirectory($dir, $excludePatterns); preload($basePath . $file);
} }
// ============================================================================= // =============================================================================
// PHASE 6: LARAVEL OCTANE (High Performance Server) // 5. SYMFONY HTTP (Used by Laravel)
// ============================================================================= // =============================================================================
preloadDirectory($basePath . '/vendor/laravel/octane/src', $excludePatterns); $symfonyHttp = [
'/vendor/symfony/http-foundation/Request.php',
// ============================================================================= '/vendor/symfony/http-foundation/Response.php',
// PHASE 7: LARAVEL PASSPORT (API Authentication) '/vendor/symfony/http-foundation/HeaderBag.php',
// ============================================================================= '/vendor/symfony/http-foundation/ParameterBag.php',
'/vendor/symfony/http-foundation/InputBag.php',
preloadDirectory($basePath . '/vendor/laravel/passport/src', $excludePatterns); '/vendor/symfony/http-foundation/FileBag.php',
preloadDirectory($basePath . '/vendor/league/oauth2-server/src', $excludePatterns); '/vendor/symfony/http-foundation/ServerBag.php',
preloadDirectory($basePath . '/vendor/lcobucci/jwt/src', $excludePatterns); '/vendor/symfony/http-foundation/Session/Session.php',
preloadDirectory($basePath . '/vendor/lcobucci/clock/src', $excludePatterns); '/vendor/symfony/http-foundation/Cookie.php',
'/vendor/symfony/http-kernel/HttpKernel.php',
// =============================================================================
// PHASE 8: LIVEWIRE 3
// =============================================================================
preloadDirectory($basePath . '/vendor/livewire/livewire/src', $excludePatterns);
preloadDirectory($basePath . '/vendor/livewire/volt/src', $excludePatterns);
// =============================================================================
// PHASE 9: FILAMENT 3 (Admin Panel)
// =============================================================================
$filamentPackages = [
// Core
$basePath . '/vendor/filament/filament/src',
$basePath . '/vendor/filament/support/src',
// Components
$basePath . '/vendor/filament/forms/src',
$basePath . '/vendor/filament/tables/src',
$basePath . '/vendor/filament/actions/src',
$basePath . '/vendor/filament/infolists/src',
$basePath . '/vendor/filament/notifications/src',
$basePath . '/vendor/filament/widgets/src',
// Spatie integration
$basePath . '/vendor/filament/spatie-laravel-media-library-plugin/src',
$basePath . '/vendor/filament/spatie-laravel-settings-plugin/src',
$basePath . '/vendor/filament/spatie-laravel-tags-plugin/src',
$basePath . '/vendor/filament/spatie-laravel-translatable-plugin/src',
]; ];
foreach ($filamentPackages as $dir) { foreach ($symfonyHttp as $file) {
preloadDirectory($dir, $excludePatterns); preload($basePath . $file);
} }
// ============================================================================= // =============================================================================
// PHASE 10: BLADE ICONS (Multiple icon sets you're using) // 6. LIVEWIRE CORE
// ============================================================================= // =============================================================================
$bladeIconPackages = [ $livewireCore = [
$basePath . '/vendor/blade-ui-kit/blade-icons/src', '/vendor/livewire/livewire/src/Livewire.php',
$basePath . '/vendor/blade-ui-kit/blade-heroicons/src', '/vendor/livewire/livewire/src/Component.php',
$basePath . '/vendor/andreiio/blade-remix-icon/src', '/vendor/livewire/livewire/src/LivewireManager.php',
$basePath . '/vendor/codeat3/blade-coolicons/src', '/vendor/livewire/livewire/src/ComponentHook.php',
$basePath . '/vendor/codeat3/blade-devicons/src',
$basePath . '/vendor/codeat3/blade-file-icons/src',
$basePath . '/vendor/codeat3/blade-vaadin-icons/src',
$basePath . '/vendor/faisal50x/blade-ionicons/src',
$basePath . '/vendor/postare/blade-mdi/src',
]; ];
foreach ($bladeIconPackages as $dir) { foreach ($livewireCore as $file) {
preloadDirectory($dir, $excludePatterns); preload($basePath . $file);
} }
// ============================================================================= // =============================================================================
// PHASE 11: SPATIE PACKAGES // 7. FILAMENT CORE
// ============================================================================= // =============================================================================
$spatiePackages = [ $filamentCore = [
$basePath . '/vendor/spatie/laravel-cookie-consent/src', '/vendor/filament/filament/src/FilamentManager.php',
$basePath . '/vendor/spatie/laravel-query-builder/src', '/vendor/filament/filament/src/Panel.php',
$basePath . '/vendor/spatie/laravel-package-tools/src', '/vendor/filament/support/src/Facades/FilamentView.php',
'/vendor/filament/forms/src/Form.php',
'/vendor/filament/tables/src/Table.php',
'/vendor/filament/actions/src/Action.php',
]; ];
foreach ($spatiePackages as $dir) { foreach ($filamentCore as $file) {
preloadDirectory($dir, $excludePatterns); preload($basePath . $file);
} }
// ============================================================================= // =============================================================================
// PHASE 12: OTHER CRITICAL DEPENDENCIES // 8. APPLICATION CODE
// ============================================================================= // =============================================================================
// Carbon (DateTime handling) // Controllers
preloadDirectory($basePath . '/vendor/nesbot/carbon/src', $excludePatterns); preloadDir($basePath . '/app/Http/Controllers');
// Monolog (Logging) // Middleware
preloadDirectory($basePath . '/vendor/monolog/monolog/src', $excludePatterns); preloadDir($basePath . '/app/Http/Middleware');
// Flysystem (File storage) // Livewire Components
preloadDirectory($basePath . '/vendor/league/flysystem/src', $excludePatterns); preloadDirRecursive($basePath . '/app/Livewire', 3);
preloadDirectory($basePath . '/vendor/league/flysystem-local/src', $excludePatterns);
// Guzzle HTTP (API calls) // Providers
preloadDirectory($basePath . '/vendor/guzzlehttp/guzzle/src', $excludePatterns); preloadDir($basePath . '/app/Providers');
preloadDirectory($basePath . '/vendor/guzzlehttp/psr7/src', $excludePatterns);
preloadDirectory($basePath . '/vendor/guzzlehttp/promises/src', $excludePatterns);
// DomPDF (PDF generation) // Classes & Helpers
preloadDirectory($basePath . '/vendor/barryvdh/laravel-dompdf/src', $excludePatterns); preloadDir($basePath . '/app/Classes');
preloadDirectory($basePath . '/vendor/dompdf/dompdf/src', $excludePatterns); preloadDir($basePath . '/app/Helpers');
preloadDir($basePath . '/app/Traits');
// QR Code // Admin Resources (Filament)
preloadDirectory($basePath . '/vendor/endroid/qr-code/src', $excludePatterns); preloadDir($basePath . '/app/Admin/Resources');
preloadDir($basePath . '/app/Admin/Pages');
// Two Factor Auth // Jobs
preloadFile($basePath . '/vendor/robthree/twofactorauth/lib/TwoFactorAuth.php'); preloadDir($basePath . '/app/Jobs');
preloadDirectory($basePath . '/vendor/robthree/twofactorauth/lib', $excludePatterns);
// Laravel Socialite (Social auth)
preloadDirectory($basePath . '/vendor/laravel/socialite/src', $excludePatterns);
preloadDirectory($basePath . '/vendor/socialiteproviders/discord/src', $excludePatterns);
preloadDirectory($basePath . '/vendor/socialiteproviders/manager/src', $excludePatterns);
// ApexCharts
preloadDirectory($basePath . '/vendor/akaunting/laravel-apexcharts/src', $excludePatterns);
// Laravel Trend
preloadDirectory($basePath . '/vendor/flowframe/laravel-trend/src', $excludePatterns);
// Laravel Themer
preloadDirectory($basePath . '/vendor/qirolab/laravel-themer/src', $excludePatterns);
// JSON API
preloadDirectory($basePath . '/vendor/timacdonald/json-api/src', $excludePatterns);
// Cookie Consent
preloadDirectory($basePath . '/vendor/whitecube/laravel-cookie-consent/src', $excludePatterns);
// Ramsey UUID
preloadDirectory($basePath . '/vendor/ramsey/uuid/src', $excludePatterns);
preloadDirectory($basePath . '/vendor/ramsey/collection/src', $excludePatterns);
// Doctrine (DBAL for migrations, Inflector for pluralization)
preloadDirectory($basePath . '/vendor/doctrine/inflector/lib', $excludePatterns);
preloadDirectory($basePath . '/vendor/doctrine/lexer/src', $excludePatterns);
// Vite manifest helper
preloadDirectory($basePath . '/vendor/laravel/framework/src/Illuminate/Foundation/Vite', $excludePatterns);
// ============================================================================= // =============================================================================
// PHASE 13: APPLICATION CODE (Your Code - Highest Priority) // 9. COMPILED VIEWS (Top 100)
// ============================================================================= // =============================================================================
// Models (most frequently accessed) $viewsPath = $basePath . '/storage/framework/views';
$modelFiles = [ if (is_dir($viewsPath)) {
$basePath . '/app/Models/User.php', $views = glob($viewsPath . '/*.php');
$basePath . '/app/Models/Service.php', if ($views) {
$basePath . '/app/Models/Product.php', usort($views, fn($a, $b) => filemtime($b) <=> filemtime($a));
$basePath . '/app/Models/Invoice.php', foreach (array_slice($views, 0, 100) as $view) {
$basePath . '/app/Models/InvoiceItem.php', preload($view);
$basePath . '/app/Models/InvoiceTransaction.php', }
$basePath . '/app/Models/Order.php',
$basePath . '/app/Models/Ticket.php',
$basePath . '/app/Models/TicketMessage.php',
$basePath . '/app/Models/Gateway.php',
$basePath . '/app/Models/Server.php',
$basePath . '/app/Models/Category.php',
$basePath . '/app/Models/Price.php',
$basePath . '/app/Models/Plan.php',
$basePath . '/app/Models/ConfigOption.php',
$basePath . '/app/Models/Coupon.php',
$basePath . '/app/Models/Property.php',
$basePath . '/app/Models/Extension.php',
$basePath . '/app/Models/Currency.php',
$basePath . '/app/Models/Setting.php',
$basePath . '/app/Models/Session.php',
$basePath . '/app/Models/Role.php',
$basePath . '/app/Models/ServiceConfig.php',
$basePath . '/app/Models/ServiceCancellation.php',
$basePath . '/app/Models/ServiceUpgrade.php',
$basePath . '/app/Models/TaxRate.php',
$basePath . '/app/Models/EmailTemplate.php',
$basePath . '/app/Models/Credit.php',
$basePath . '/app/Models/ApiKey.php',
$basePath . '/app/Models/AuditLog.php',
];
preloadFiles($modelFiles);
// Preload remaining models
preloadDirectory($basePath . '/app/Models', $excludePatterns);
// Core application directories
$appDirectories = [
// HTTP Layer
$basePath . '/app/Http/Controllers',
$basePath . '/app/Http/Middleware',
$basePath . '/app/Http/Requests',
// Livewire Components (critical for UI)
$basePath . '/app/Livewire',
// Filament Admin Panel
$basePath . '/app/Admin/Resources',
$basePath . '/app/Admin/Pages',
$basePath . '/app/Admin/Widgets',
$basePath . '/app/Admin/Components',
$basePath . '/app/Admin/Actions',
$basePath . '/app/Admin/Clusters',
// Service Providers
$basePath . '/app/Providers',
// Background Jobs
$basePath . '/app/Jobs',
// Events & Listeners
$basePath . '/app/Events',
$basePath . '/app/Listeners',
// Observers
$basePath . '/app/Observers',
// Policies
$basePath . '/app/Policies',
// Classes & Helpers
$basePath . '/app/Classes',
$basePath . '/app/Helpers',
$basePath . '/app/Support',
$basePath . '/app/Traits',
// Validation Rules
$basePath . '/app/Rules',
// Mail
$basePath . '/app/Mail',
// View Components
$basePath . '/app/View',
// Attributes
$basePath . '/app/Attributes',
// Exceptions
$basePath . '/app/Exceptions',
// Console Commands
$basePath . '/app/Console/Commands',
];
foreach ($appDirectories as $dir) {
preloadDirectory($dir, $excludePatterns);
}
// =============================================================================
// PHASE 14: EXTENSIONS (Payment Gateways, Servers, etc.)
// =============================================================================
$extensionDirs = [
$basePath . '/extensions/Gateways',
$basePath . '/extensions/Servers',
$basePath . '/extensions/Others',
];
foreach ($extensionDirs as $dir) {
preloadDirectory($dir, $excludePatterns);
}
// =============================================================================
// PHASE 15: THEMES
// =============================================================================
preloadDirectory($basePath . '/themes/lucentui', $excludePatterns);
// =============================================================================
// PHASE 16: COMPILED BLADE VIEWS (Most Recent)
// =============================================================================
$compiledViewsPath = $basePath . '/storage/framework/views';
if (is_dir($compiledViewsPath)) {
$viewFiles = glob($compiledViewsPath . '/*.php');
if ($viewFiles) {
// Sort by modification time, newest first
usort($viewFiles, static fn($a, $b) => filemtime($b) <=> filemtime($a));
// Preload top 500 most recently used views
$viewFiles = array_slice($viewFiles, 0, 500);
preloadFiles($viewFiles);
} }
} }
// ============================================================================= // =============================================================================
// PHASE 17: CONFIG FILES // SUMMARY
// ============================================================================= // =============================================================================
preloadDirectory($basePath . '/config', $excludePatterns);
preloadFile($basePath . '/bootstrap/app.php');
preloadFile($basePath . '/bootstrap/providers.php');
// =============================================================================
// PRELOAD SUMMARY & LOGGING
// =============================================================================
$stats['end_time'] = hrtime(true);
$stats['end_memory'] = memory_get_usage(true);
$duration = round(($stats['end_time'] - $stats['start_time']) / 1e6, 2); // ms
$memoryUsed = round(($stats['end_memory'] - $stats['start_memory']) / 1024 / 1024, 2); // MB
$totalMemory = round($stats['end_memory'] / 1024 / 1024, 2); // MB
$summary = sprintf(
'OPcache Preload: %d files preloaded, %d skipped in %.2fms (Memory: %.2fMB used, %.2fMB total)',
$stats['preloaded'],
$stats['skipped'],
$duration,
$memoryUsed,
$totalMemory
);
// Log summary
if (PHP_SAPI === 'cli') { if (PHP_SAPI === 'cli') {
echo $summary . PHP_EOL; $mem = round(memory_get_usage(true) / 1024 / 1024, 1);
echo "OPcache Preload: {$count} files, {$mem}MB memory\n";
if (!empty($stats['errors'])) {
echo "Errors (" . count($stats['errors']) . "):\n";
foreach (array_slice($stats['errors'], 0, 10) as $error) {
echo " - {$error}\n";
}
if (count($stats['errors']) > 10) {
echo " ... and " . (count($stats['errors']) - 10) . " more errors\n";
}
}
// Show OPcache status
if (function_exists('opcache_get_status')) {
$status = opcache_get_status(false);
if ($status) {
echo sprintf(
"OPcache Status: %d cached scripts, %.2fMB memory used, %.2f%% hit rate\n",
$status['opcache_statistics']['num_cached_scripts'] ?? 0,
($status['memory_usage']['used_memory'] ?? 0) / 1024 / 1024,
$status['opcache_statistics']['opcache_hit_rate'] ?? 0
);
}
}
} else { } else {
error_log($summary); error_log("OPcache Preload: {$count} files");
} }
// Force garbage collection to free memory
gc_collect_cycles();