เพื่อให้ผู้ใช้เข้าหน้าเพจด้วยความรวดเร็วจึงต้องทำ caching เก็บส่วนที่ไม่ได้เปลี่ยนแปลงบ่อย และสามารถใช้ซ่้ำๆ ได้
เริ่มจากสร้างไฟล์เก็บ config ขึ้นมาก่อน[code language=”php” title=”\application\config\cache.php”]<?php
defined(‘BASEPATH’) or exit(‘No direct script access allowed’);
$config[‘caching’][‘adapter’] = ‘memcached’;
$config[‘caching’][‘backup’] = ‘file’;[/code]โดย
- adapter
- คือ จะเลือกใช้ driver ตัวไหนในการทำ cache ระหว่าง
Drivers Value Alternative PHP Cache (APC) Caching apc Dummy Cache dummy File-based Caching file Memcached Caching memcached Redis Caching redis WinCache Caching wincache - backup
- เป็นตัวเลือกสำรองถ้าตัวแรกไม่สามารถทำงานได้ เช่น เครื่องที่เราใช้ไม่ได้ลง Memcached ไว้ ก็จะใช้ file แทน ( cache file ถูกเก็บไว้ที่ \application\cache หรือ ตาม config $config[‘cache_path’])
โหลด Driver ได้ 2 วิธีคือ
- Auto-loading
- เหมาะกับงานที่ต้องใช้ cache บ่อยๆ ทำได้โดยเพิ่ม ‘cache’ เข้าไป[code language=”php” title=”\application\config\autoload.php”]$autoload[‘drivers’] = […, ‘cache’, …];[/code]
- load driver
- โหลด driver เฉพาะ controller ที่ต้องใช้ cache เท่านั้น[code language=”php” title=”\application\controllers\Welcome.php”] public function __construct()
{
parent::__construct();$this->load->driver(‘cache’);
}[/code]
การใช้งาน[code language=”php” title=”\application\controllers\Welcome.php”]<?php
defined(‘BASEPATH’) or exit(‘No direct script access allowed’);
class Welcome extends CI_Controller
{
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* – or –
* http://example.com/index.php/welcome/index
* – or –
* Since this controller is set as the default controller in
* config/routes.php, it’s displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$cacheKey = ‘home’ . date(‘Y-m-d’); /* unque id */
$cacheKey = mb_ereg_replace(‘([^\w\s\d\-_~,;\[\]\(\).])’, ”, $cacheKey);
if (!$datas = $this->cache->get($cacheKey)) {
$datas = $this->load->view(‘welcome_message’, ”, true);
$this->cache->save($cacheKey, $datas, 300);
}
echo $datas;
}
}[/code] เพราะว่า file driver เป็นการเขียนไฟล์ลงบน hard disk จริงๆ จึงควรแน่ใจว่าไฟล์ถูกรูปแบบที่ os สามารถเขียนไฟล์ได้ โดนอาจจะใช้ md5 เข้ารหัส $cacheKey ก่อน[code language=”php”]$cacheKey = md5($cacheKey);[/code] หรือใช้ [code language=”php”]$cacheKey = mb_ereg_replace(‘([^\w\s\d\-_~,;\[\]\(\).])’, ”, $cacheKey);[/code]
อ่านเพิ่มเติม