Codeigniter Cache Libraries

Posted June 25th, 2010 in News by Gevork

ci_logo_flame-150x150Hi there.. I am not sleeping and searching for a good library to use . I am looking a multipurpose cache library for my social network made on codeigniter. So Now question about the scaling stands out and I am gonna to integrate some memcache .

So will do parallel list of all found libs. Maybe you will need it.

  1. Elliot Haughin’s Codeignuter Multicache Library (memcache , PHPCache) download
  2. Khaos::Khcache(eAccelerator, APC und XCache)  download
  3. Cache Library (memcache, file)    download

Add some more in comments if you know

Правильный Кешинг для CodeIgniter

Posted January 25th, 2010 in News by Gevork

Привет… Тебе наверное понадобился правильный или частичний Кешинг для CI?Ну  Скажем вам надо частично скешировать ваш код для далнейших действий. Тогда не ломайте голову!.

Качаем сначала KhCache (http://codeigniter.com/forums/viewthread/69843/) от  Khaosа.

1. Инсталл

Кидаем его в папку /application/libraries/

И начинаем юзать.

Если захотите переписать дефолтовые значения , те параметры библиотеки, то в папке /application/config создаем Khaos.php

И в нем пишем

$config['cache'] = array('container' => 'File',
                         'ttl'       => 3600,
                         'File'      => array('store'           => BASEPATH.'cache/',
                                              'auto_clean'      => 10,
                                              'auto_clean_life' => 3600,
                                              'auto_clean_all'  => false));

Все думаю понятно. Если захоите вместо контейнера File  использовать скажем XCache Надо немножко помудить
с библиотекой

А в конфиге Написать так например

 $config['cache'] = array('container' => 'APC');  

Для чего отвечают отдельные ключи в массиве? 

auto_clean - By default there is a 1 in 10 chance of the cache dir being cleaned, set to false to disable.
 auto_clean_life - Files older than this will be removed.
 auto_clean_all - By default only cache files prefixed with khcache_ are removed set to true to have khcache clean the entire directory

2. Использование

Для того чтоб использовать
  • $this->khcache->generatekey(): Делает Идентификатор Кеша чтоб потом мы смогли достать его.
  • $this->khcache->store($key, $data, $ttl): Сохраняет ($data) под идентификатром ($key) на время $ttl секунд в Кеш.
  • $this->khcache->call($func, $args, $ttl): Делает функцию ($func) с аргументами ($args, Typ: Array) и сохраняет ответ на $ttl Секунд в кеш.
  • $this->khcache->fetch($key):Читает элемент информации, который под ключом $key спрятан в кеше.
  • $this->khcache->delete($key): Удаляет элемент информации под ключом $key из кеша.
  • $this->khcache->delete_all($key): Удаляет все элементы из Кеша.
  • $this->khcache->get_hits(): Дает все успешные вызовы функции кеша (Benchmarking).
  • $this->khcache->get_misses(): Дает количество безуспешных вызовов (Benchmarking).
Надеюсь Понятно перевел.

3. Плагины Контейнеров

Если ты XCache как контейнер хочешь юзать, то введи след код в конце библиотекы
 1 /**
 2 * Khaos :: KhCache :: XCache
 3 *
 4 * Wraps the XCache extension so it can be used
 5 * as an KhCache Container.
 6 *
 7 */
 8 class KH_Cache_XCache
 9 {
10     /**
11      * Constructor
12      *
13      * @param array $options   Container Options
14      *
15      * @return KH_Cache_XCache
16      */
17     function __construct($options)
18     {
19         // Ensure XCache is available
20         if (!extension_loaded('xcache') || !ini_get('xcache.cacher') || ini_get('xcache.var_size') == 0)
21          show_error('Khaos :: Cache :: XCache - One or more of the required XCACHE functions
22            is unavailable.');
23     }
24
25     /**
26      * Store Cache Item
27      *
28      * @param string $key
29      * @param mixed  $data
30      * @param int    $ttl
31      *
32      * @return bool
33      * @access public
34      */
35     function Store($key, $data, $ttl)
36     {
37         return xcache_set($key, serialize($data), $ttl);
38     }
39
40     /**
41      * Fetch Cache Item
42      *
43      * @param string $key
44      *
45      * @return mixed
46      * @access public
47      */
48     function Fetch($key)
49     {
50         return (($ret = xcache_get($key)) !== false)?unserialize($ret):false;
51     }
52
53     /**
54      * Delete Cache Item
55      *
56      * @param string $key
57      *
58      * @return bool
59      * @access public
60      */
61     function Delete($key)
62     {
63         return xcache_unset($key);
64     }
65
66     /**
67      * Delete All Cache Items
68      *
69      * @return bool
70      * @access public
71      */
72     function DeleteAll()
73     {
74         $xcache_auth = ini_get('xcache.admin.enable_auth');
75         ini_set('xcache.admin.enable_auth', 0);
76         for ($v=0; ini_get('xcache.var_count'); $v++)
77             xcache_clear_cache(XC_TYPE_VAR, $v);
78         ini_set('xcache.admin.enable_auth', $xcache_auth);
79         return true;
80     }
81 }

Для eAccelerator введи это (ВНИМАНИЕ: delete_all не будет поддержан):

 1 // ------------------------------------------------------------------------
 2
 3 /**
 4 * Khaos :: KhCache :: Eaccelerator
 5 *
 6 * Wraps the Eaccelerator extension so it can be used
 7 * as an KhCache Container.
 8 *
 9 */
10 class KH_Cache_Eaccelerator
11 {
12     /**
13      * Constructor
14      *
15      * @param array $options   Container Options
16      *
17      * @return KH_Cache_Eaccelerator
18      */
19     function KH_Cache_Eaccelerator($options)
20     {
21         // Ensure Eaccelerator is available
22         if (!function_exists('eaccelerator_put')
23          || !function_exists('eaccelerator_get')
24          || !function_exists('eaccelerator_rm'))
25          show_error('Khaos :: Cache :: Eaccelerator - One or more of the required Eaccelerator functions
26            is unavailable.');
27     }
28
29     /**
30      * Store Cache Item
31      *
32      * @param string $key
33      * @param mixed  $data
34      * @param int    $ttl
35      *
36      * @return bool
37      * @access public
38      */
39     function Store($key, $data, $ttl)
40     {
41         return eaccelerator_put($key, serialize($data), $ttl);
42     }
43
44     /**
45      * Fetch Cache Item
46      *
47      * @param string $key
48      *
49      * @return mixed
50      * @access public
51      */
52     function Fetch($key)
53     {
54         return (($ret = eaccelerator_get($key)) !== NULL) ? unserialize($ret) : FALSE;
55     }
56
57     /**
58      * Delete Cache Item
59      *
60      * @param string $key
61      *
62      * @return bool
63      * @access public
64      */
65     function Delete($key)
66     {
67         return eaccelerator_rm($key);
68     }
69
70     /**
71      * Delete All Cache Items
72      *
73      * @return bool
74      * @access public
75      */
76     function DeleteAll()
77     {
78         //return apc_clear_cache('user');
79         //Not available in eaccelerator
80         return FALSE;
81     }
82 }

Ну все если че, и ты по немецки понимаешь то плиз читай вот это: http://wiki.codeigniter.ch/wiki/ci-wiki/Partielles_Caching_mit_KhCache