OPcache ปรับปรุง Performance โดย Cache Compiled Bytecode แต่บางครั้งก่อให้เกิด Bug ที่ยากต่อการ Debug (Stale Cache, Corruption, Incompatibility)
1. ปิด OPcache ชั่วคราว (Quick Test)
ถ้า Bug หายเมื่อปิด OPcache → ปัญหาอยู่ที่ OPcache
2. เปิด Error Reporting เต็มที่
ini_set('display_errors', '1');
error_reporting(E_ALL); // หรือ -1 (ทั้งหมด)
// ใน php.ini
// display_errors = On
// error_reporting = E_ALL
// log_errors = On
// error_log = /var/log/php_errors.log
3. OPcache Configuration สำหรับ Development
; php.ini หรือ .user.ini
opcache.enable=1
opcache.enable_cli=1
; Development: Revalidate ทุกครั้ง (ไม่ Cache)
opcache.validate_timestamps=1
opcache.revalidate_freq=0 ; 0 = Check ทุก Request
; Production: Revalidate ทุก N วินาที
; opcache.validate_timestamps=1
; opcache.revalidate_freq=60
; Logging
opcache.error_log=/var/log/opcache.log
opcache.log_verbosity_level=3 ; 1=Fatal, 2=Error, 3=Warning, 4=Info, 5=Debug
; Memory
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.interned_strings_buffer=16
4. Clear OPcache แบบ Manual
5. ตรวจสอบ OPcache Status
true/false
['cache_full'] => true/false (Cache เต็ม)
['wasted_percentage'] => % Memory ที่ Waste
['num_cached_scripts'] => จำนวนไฟล์ที่ Cache
['hit_rate'] => Cache Hit Rate (%)
*/
// ดู Scripts ที่ Cache
$scripts = $status['scripts'] ?? [];
foreach ($scripts as $path => $info) {
echo "$path: {$info['memory_consumption']} bytes, hits: {$info['hit_count']}\n";
}
6. ใช้ Xdebug (Debugger จริง)
OPcache และ Xdebug ทำงานร่วมได้ แต่ Xdebug จะ Disable OPcache สำหรับไฟล์ที่ Debug อยู่
; php.ini (Development)
zend_extension=xdebug.so
xdebug.mode=debug,develop,trace
xdebug.client_host=127.0.0.1
xdebug.client_port=9003
xdebug.start_with_request=trigger
; OPcache ยังคงทำงานสำหรับไฟล์อื่น
opcache.enable=1
7. Common OPcache Issues และ Fix
| อาการ | สาเหตุ | แก้ไข |
|---|---|---|
| Code ใหม่ไม่ Run (Run Code เก่า) | Cache ไม่ Invalidate | opcache.validate_timestamps=1, revalidate_freq=0 (Dev) |
| Fatal Error: Cannot redeclare class | Cache Corrupt / Symlink Issue | opcache_reset(), Restart PHP-FPM |
| Segfault / Crash | Incompatible Extension / Bug | Update PHP, Disable JIT, Check Extensions |
| Memory Exhausted | opcache.memory_consumption น้อยเกิน | เพิ่มเป็น 256MB+ |
| File ถูก Delete แต่ยัง Cache | opcache.enable_file_override=1 | ตั้งค่า 0 หรือ Restart |
8. JIT (PHP 8.0+) และ OPcache
; php.ini
opcache.jit_buffer_size=100M
opcache.jit=1255 (tracing) หรือ function
; หากมีปัญหา: ปิด JIT
opcache.jit=off
Best Practice Checklist
- ☐ Development:
validate_timestamps=1, revalidate_freq=0 - ☐ Production:
validate_timestamps=1, revalidate_freq=60(หรือ 0 + Deploy Script Clear Cache) - ☐ Deploy Script: เรียก
opcache_reset()หรือ Restart PHP-FPM หลัง Deploy - ☐ Monitor:
opcache_get_status()- Hit Rate > 90%, Wasted < 10% - ☐ Preload (PHP 7.4+): ใช้
opcache.preloadสำหรับ Framework Core