Get Smarty

Donate

Donate Bitcoin Bitcoin
Paypal

Smarty Icon

You may use the Smarty logo according to the trademark notice.

Smarty Template Engine Smarty Template Engine

For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty

Buy cheap eyeglasses from Cheapglasses123.com and save up to 80%.

Buy prescription glasses from www.australiaglasses.com and save.

Cheap Glasses Now On Sale at GlassesPeople.com. Starts At $7.95.

Where to buy discount wedding dresses and cheap smart dresses free shipping - Weddingdresstrend.com

Brautkleider auf Topwedding.de

Find free files to download on allwhatyouwant.net

Looking For Affordable Wedding Dresses 2015 at Best Prices On TDBridal.com

Shop high quality cheap prom dresses on Dresswe.co.uk

Buy New Arrival Cheap Prom Dresses 2015 at JDBRIDAL Prom Dress Store

Advertisement

自定义缓存实现

Smarty默认是使用基于文件的缓存机制,作为�选的方案,你�以自定义一套缓存机制的实现,�进行缓存文件的读写和删除。

Note

Smarty2使用$cache_handler_func的回调函数�实现此功能。 而Smarty3使用了Smarty_CacheResource模��实现。

自定义缓存实现�以实现类似下�的目的: 用更快的存储引擎�替代较慢的文件系统, 使缓存�以分布到多��务器上。

Smarty�以通过API Smarty_CacheResource_Custom 或者 Smarty_CacheResource_KeyValueStore �实现缓存机制。 Smarty_CacheResource_Custom是比较简�的API,直接通过覆盖读�写�删除等�作�实现缓存机制。 该API�以使用于任何你觉得适�的方�,或存储到任何你觉得适�的地方。 Smarty_CacheResource_KeyValueStore的API�让你使用K-V存储模�(比如APC,Memcache等)�实现缓存机制。 更进一步,就算是多层的缓存组如"a|b|c",该API也让你�以通过删除缓存组"a"�将整个嵌套的缓存组删除, �使K-V存储机制本身无法实现这�层次结构的存储。

自定义缓存�以放到$plugins_dir目录下并命�为cacheresource.foobarxyz.php, 或者在�行时通过registerCacheResource() �进行注册。 上�两�方�都必须设置$caching_type ��动你的自定义缓存机制。

Example 15.15. 通过MySQL实现自定义缓存机制


<?php

require_once 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->caching_type = 'mysql';

/**
 * MySQL 缓存
 *
 * 通过自定义缓存的接�API,让MySQL�作为Smarty的输出缓存存储器。
 *
 * 表定义:
 * <pre>CREATE TABLE IF NOT EXISTS `output_cache` (
 *   `id` CHAR(40) NOT NULL COMMENT 'sha1 hash',
 *   `name` VARCHAR(250) NOT NULL,
 *   `cache_id` VARCHAR(250) NULL DEFAULT NULL,
 *   `compile_id` VARCHAR(250) NULL DEFAULT NULL,
 *   `modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
 *   `content` LONGTEXT NOT NULL,
 *   PRIMARY KEY (`id`),
 *   INDEX(`name`),
 *   INDEX(`cache_id`),
 *   INDEX(`compile_id`),
 *   INDEX(`modified`)
 * ) ENGINE = InnoDB;</pre>
 *
 * @package CacheResource-examples
 * @author Rodney Rehm
 */
class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
    // PDO 对象
    protected $db;
    protected $fetch;
    protected $fetchTimestamp;
    protected $save;
    
    public function __construct() {
        try {
            $this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty");
        } catch (PDOException $e) {
            throw new SmartyException('Mysql �无法链接: ' . $e->getMessage());
        }
        $this->fetch = $this->db->prepare('SELECT modified, content FROM output_cache WHERE id = :id');
        $this->fetchTimestamp = $this->db->prepare('SELECT modified FROM output_cache WHERE id = :id');
        $this->save = $this->db->prepare('REPLACE INTO output_cache (id, name, cache_id, compile_id, content)
            VALUES  (:id, :name, :cache_id, :compile_id, :content)');
    }

    /**
	 * 从数�表中获�缓存的内容�修改时间
     *
     * @param string $id 缓存内容的唯一识别ID
     * @param string $name 模��称
     * @param string $cache_id 缓存ID
     * @param string $compile_id 编译ID
     * @param string $content (引用的)缓存内容
     * @param integer $mtime 缓存修改的时间戳 (epoch)
     * @return void
     */
    protected function fetch($id, $name, $cache_id, $compile_id, &$content, &$mtime)
    {
        $this->fetch->execute(array('id' => $id));
        $row = $this->fetch->fetch();
        $this->fetch->closeCursor();        
        if ($row) {
            $content = $row['content'];
            $mtime = strtotime($row['modified']);
        } else {
            $content = null;
            $mtime = null;
        }
    }
    
    /**
	 * 从数�表中获�缓存的修改时间
     *
     * @note 这是个�选的实现接�。在你确定仅获�修改时间会比获�整个内容�更快的时候,使用此接�。
     * @param string $id 缓存内容的唯一识别ID
     * @param string $name 模��称
     * @param string $cache_id 缓存ID
     * @param string $compile_id 编译ID
     * @return integer|boolean 返回模�修改时间,如果找�到缓存则返回false
     */
    protected function fetchTimestamp($id, $name, $cache_id, $compile_id)
    {
        $this->fetchTimestamp->execute(array('id' => $id));
        $mtime = strtotime($this->fetchTimestamp->fetchColumn());
        $this->fetchTimestamp->closeCursor();
        return $mtime;
    }
    
    /**
     * �存缓存内容到数�表
     *
     * @param string $id 缓存内容的唯一识别ID
     * @param string $name 模��称
     * @param string $cache_id 缓存ID
     * @param string $compile_id 编译ID
     * @param integer|null $exp_time 缓存过期时间,或null
     * @param string $content 需�缓存的内容
     * @return boolean �功true,失败false
     */
    protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content)
    {
        $this->save->execute(array(
            'id' => $id,
            'name' => $name,
            'cache_id' => $cache_id,
            'compile_id' => $compile_id,
            'content' => $content,
        ));
        return !!$this->save->rowCount();
    }
    
    /**
     * 从数�表中删除缓存
     *
     * @param string $name 模��称
     * @param string $cache_id 缓存ID
     * @param string $compile_id 编译ID
     * @param integer|null $exp_time 缓存过期时间,或null
     * @return integer 返回被删除的缓存数�
     */
    protected function delete($name, $cache_id, $compile_id, $exp_time)
    {
        // 删除整个缓存
        if ($name === null && $cache_id === null && $compile_id === null && $exp_time === null) {
			// 返回删除缓存记录的数�,需��进行一次查询�计算。
            $query = $this->db->query('TRUNCATE TABLE output_cache');
            return -1;
        }
        // 组�查找�件
        $where = array();
        // 匹��称
        if ($name !== null) {
            $where[] = 'name = ' . $this->db->quote($name);
        }
        // 匹�编译ID
        if ($compile_id !== null) {
            $where[] = 'compile_id = ' . $this->db->quote($compile_id);
        }
        // 匹�过期时间范围
        if ($exp_time !== null) {
            $where[] = 'modified < DATE_SUB(NOW(), INTERVAL ' . intval($exp_time) . ' SECOND)';
        }
        // 匹�缓存ID和缓存组的�ID
        if ($cache_id !== null) {
            $where[] = '(cache_id = '. $this->db->quote($cache_id)
                . ' OR cache_id LIKE '. $this->db->quote($cache_id .'|%') .')';
        }
        // 执行删除
        $query = $this->db->query('DELETE FROM output_cache WHERE ' . join(' AND ', $where));
        return $query->rowCount();
    }
}
?>

   

Example 15.16. 通过Memcache实现自定义缓存机制


<?php

require_once 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->caching_type = 'memcache';

/**
 * Memcache 缓存
 *
 * 通过K-V存储的API�把memcache作为Smarty的输出缓存器。
 *
 * 注�memcache�求key的长度�能是256个字符以内,
 * 所以程�中,key都进行sha1哈希计算��使用。
 *
 * @package CacheResource-examples
 * @author Rodney Rehm
 */
class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
    /**
     * memcache 对象
     * @var Memcache
     */
    protected $memcache = null;
    
    public function __construct()
    {
        $this->memcache = new Memcache();
        $this->memcache->addServer( '127.0.0.1', 11211 );
    }
    
    /**
	 * 从memcache中获�一系列key的值。
     *
     * @param array $keys 多个key
     * @return array 按key的顺�返回的对应值
     * @return boolean �功返回true,失败返回false
     */
    protected function read(array $keys)
    {
        $_keys = $lookup = array();
        foreach ($keys as $k) {
            $_k = sha1($k);
            $_keys[] = $_k;
            $lookup[$_k] = $k;
        }
        $_res = array();
        $res = $this->memcache->get($_keys);
        foreach ($res as $k => $v) {
            $_res[$lookup[$k]] = $v;
        }
        return $_res;
    }
    
    /**
	 * 将一系列的key对应的值存储到memcache中。
     *
     * @param array $keys 多个kv对应的数�值
     * @param int $expire 过期时间
     * @return boolean �功返回true,失败返回false
     */
    protected function write(array $keys, $expire=null)
    {
        foreach ($keys as $k => $v) {
            $k = sha1($k);
            $this->memcache->set($k, $v, 0, $expire);
        }
        return true;
    }

    /**
	 * 从memcache中删除
     *
     * @param array $keys 待删除的多个key
     * @return boolean �功返回true,失败返回false
     */
    protected function delete(array $keys)
    {
        foreach ($keys as $k) {
            $k = sha1($k);
            $this->memcache->delete($k);
        }
        return true;
    }

    /**
     * 清空全部的值
     *
     * @return boolean �功返回true,失败返回false
     */
    protected function purge()
    {
        return $this->memcache->flush();
    }
}
?>

   

Comments
No comments for this page.
Post a Comment
All comments are moderated. Support questions are ignored, use the forums instead.
Author:
Email: (not shown)
What is 11 plus 7? (Are you human?)

Advertisement