APC Backend Cache

Всем доброго времени суток!
Хочу поделиться с вами небольшим файликом, который даст возможность использовать DklabCache с APC хранилищем.

Каждый для себя решает сам: нужно это ему или нет.
Чтобы далеко по поисковикам не лазить, вот небольшие мои тесты:
10000 итераций по 1 байту
10000 итераций по 1 байту
Этот тест нельзя назвать по поведению близкому к веб, если у вас не хайлоад проект.

10000 итераций по 32 байта
10000 итераций по 32 байта
Сам Backend файл кладем по адресу:
DkLabCache/Zend/Cache/Backend/Apc.php
Содержимое:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright © 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * @see Zend_Cache_Backend_Interface
 */
require_once 'Zend/Cache/Backend/Interface.php';

/**
 * @see Zend_Cache_Backend
 */
require_once 'Zend/Cache/Backend.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright © 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Backend_APC extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
    /**
     * Persistent
     */
    const DEFAULT_PERSISTENT = true;

    /**
     * Constructor
     *
     * @param array $options associative array of options
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function __construct($options = array())
    {
        if (!extension_loaded('apc')) {
            Zend_Cache::throwException('The apc extension must be loaded for using this backend !');
        }
    }

    /**
     * Test if a cache is available for the given id and (if yes) return it (false else)
     *
     * @param  string  $id                     Cache id
     * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
     * @return string|false cached datas
     */
    public function load($id, $doNotTestCacheValidity = false)
    {
        // WARNING : $doNotTestCacheValidity is not supported !!!
        if ($doNotTestCacheValidity) {
            $this->_log("Zend_Cache_Backend_APC::load() : \$doNotTestCacheValidity=true is unsupported by the APC backend");
        }

        $tmp = apc_fetch($id);
        if (is_array($tmp)) {
            return $tmp[0];
        }
        return false;
    }

    /**
     * Test if a cache is available or not (for the given id)
     *
     * @param  string $id Cache id
     * @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
     */
    public function test($id)
    {
        $tmp = apc_fetch($id);
        if (is_array($tmp)) {
            return $tmp[1];
        }
        return false;
    }

    /**
     * Save some string datas into a cache record
     *
     * Note : $data is always "string" (serialization is done by the
     * core not by the backend)
     *
     * @param  string $data             Datas to cache
     * @param  string $id               Cache id
     * @param  array  $tags             Array of strings, the cache record will be tagged by each string entry
     * @param  int    $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
     * @return boolean True if no problem
     */
    public function save($data, $id, $tags = array(), $specificLifetime = false)
    {
        $lifetime = $this->getLifetime($specificLifetime);

        $result = apc_store($id, array($data, time()), $lifetime);
        return $result;
    }

    /**
     * Remove a cache record
     *
     * @param  string $id Cache id
     * @return boolean True if no problem
     */
    public function remove($id)
    {
        return apc_delete($id);
    }

    /**
     * Clean some cache records
     *
     * Available modes are :
     * 'all' (default)  => remove all cache entries ($tags is not used)
     * 'old'            => remove too old cache entries ($tags is not used)
     * 'matchingTag'    => remove cache entries matching all given tags
     *                     ($tags can be an array of strings or a single string)
     * 'notMatchingTag' => remove cache entries not matching one of the given tags
     *                     ($tags can be an array of strings or a single string)
     *
     * @param  string $mode Clean mode
     * @param  array  $tags Array of tags
     * @return boolean True if no problem
     */
    public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
    {
        return true;
    }

    /**
     * Return true if the automatic cleaning is available for the backend
     *
     * @return boolean
     */
    public function isAutomaticCleaningAvailable()
    {
        return false;
    }

}


В файл /classes/modules/sys_cache/Cache.class.php
Добавляем, чтобы получилось так:
define('SYS_CACHE_TYPE_MEMORY','memory');
define('SYS_CACHE_TYPE_APC','apc');

А также нахом строку
} elseif ($this->sCacheType==SYS_CACHE_TYPE_MEMORY) {

перед ней вставляем
} elseif ($this->sCacheType==SYS_CACHE_TYPE_APC) {
			require_once('Zend/Cache/Backend/Apc.php');
			$oCahe = new Zend_Cache_Backend_APC();
			$this->oBackendCache = new Dklab_Cache_Backend_TagEmuWrapper(new Dklab_Cache_Backend_Profiler($oCahe,array($this,'CalcStats')));


И теперь в конфиге можно указывать тип кеширования apc.

2 комментария

avatar
все сделал как описано выше, а выдало:
Fatal error: Uncaught exception 'Zend_Cache_Exception' with message 'The apc extension must be loaded for using this backend !' in /home/mydomen/domains/site.ru/public_html/classes/lib/external/DklabCache/Zend/Cache.php:141 Stack trace: #0 /home/mydomen/domains/site.ru/public_html/classes/lib/external/DklabCache/Zend/Cache/Backend/Apc.php(56): Zend_Cache::throwException('The apc extensi...') #1 /home/mydomen/domains/site.ru/public_html/classes/modules/sys_cache/Cache.class.php(76): Zend_Cache_Backend_APC->__construct() #2 /home/mydomen/domains/site.ru/public_html/classes/engine/Engine.class.php(68): LsCache->Init() #3 /home/mydomen/domains/site.ru/public_html/classes/engine/Router.class.php(99): Engine->InitModules() #4 /home/mydomen/domains/site.ru/public_html/index.php(32): Router->Exec() #5 {main} thrown in /home/mydomen/domains/site.ru/public_html/classes/lib/external/DklabCache/Zend/Cache.php on line 141
avatar
Нужно установить само APC хранилище(PHP Extension)
pecl.php.net/package/APC — это офф сайт. Как установить — дак это в гугл забейте.
"'The apc extension must be loaded for using this backend !'" — APC расширения должно быть установлено, чтобы его можно было использовать в качестве бэкенда. :)
Только зарегистрированные и авторизованные пользователи могут оставлять комментарии.