Hỏi về Cache trong php

Mọi người cho mình hỏi cơ chế hoạt động của Cache ( bộ nhớ đệm) như thế nào, khi nào thì nên dùng Cache trong php nói chung và Laravel nói riêng. Cám ơn các bạn

Bạn có thể dùng cach file.
Cớ chế thì đơn giản:

  • Lưu data xuông file
  • Đọc file ra hiển thị.

VD trên mạng đầy :slight_smile: như dưới:

<?PHP // Adapted for The Art of Web: www.the-art-of-web.com // Based on PHP code by Dennis Pallett: www.phpit.net // Please acknowledge use of this code by including this header. // location and prefix for cache files define('CACHE_PATH', "/tmp/cache_"); // how long to keep the cache files (hours) define('CACHE_TIME', 12); // return location and name for cache file function cache_file() { return CACHE_PATH . md5($_SERVER['REQUEST_URI']); } // display cached file if present and not expired function cache_display() { $file = cache_file(); // check that cache file exists and is not too old if(!file_exists($file)) return; if(filemtime($file) < time() - CACHE_TIME * 3600) return; // if so, display cache file and stop processing echo gzuncompress(file_get_contents($file)); exit; } // write to cache file function cache_page($content) { if(false !== ($f = @fopen(cache_file(), 'w'))) { fwrite($f, gzcompress($content)); fclose($f); } return $content; } // execution stops here if valid cache file found cache_display(); // enable output buffering and create cache file ob_start('cache_page'); ?>
1 Like

Khi nào dùng cache: Theo mình dữ liệu nào ít thay đổi, sử dụng thường xuyên thì đưa ra( đọc DB ra,v.v) lưu ra cache truy xuất cho nhanh.

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?