Tag Archive File-based

Byphunsanit

CodeIgniter: Cache

เพื่อให้ผู้ใช้เข้าหน้าเพจด้วยความรวดเร็วจึงต้องทำ caching เก็บส่วนที่ไม่ได้เปลี่ยนแปลงบ่อย และสามารถใช้ซ่้ำๆ ได้

เริ่มจากสร้างไฟล์เก็บ config ขึ้นมาก่อน

\application\config\cache.php
1
2
3
4
5
<?php
defined('BASEPATH') or exit('No direct script access allowed');
 
$config['caching']['adapter'] = 'memcached';
$config['caching']['backup'] = 'file';

โดย

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’ เข้าไป

\application\config\autoload.php
1
$autoload['drivers'] = [..., 'cache', ...];
load driver
โหลด driver เฉพาะ controller ที่ต้องใช้ cache เท่านั้น

\application\controllers\Welcome.php
1
2
3
4
5
6
public function __construct()
{
    parent::__construct();
 
    $this->load->driver('cache');
}

การใช้งาน

\application\controllers\Welcome.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?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>
     */
    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;
    }
 
}

เพราะว่า file driver เป็นการเขียนไฟล์ลงบน hard disk จริงๆ จึงควรแน่ใจว่าไฟล์ถูกรูปแบบที่ os สามารถเขียนไฟล์ได้ โดนอาจจะใช้ md5 เข้ารหัส $cacheKey ก่อน

1
$cacheKey = md5($cacheKey);

หรือใช้

1
$cacheKey = mb_ereg_replace('([^\w\s\d\-_~,;\[\]\(\).])', '', $cacheKey);

อ่านเพิ่มเติม