设为首页 收藏本站
查看: 965|回复: 0

[经验分享] 收藏一个Php的Cache类

[复制链接]

尚未签到

发表于 2015-8-23 17:10:27 | 显示全部楼层 |阅读模式
  Cache的作用不用说大家都知道咯,这些天也面试了一些人,发现很多人框架
  用多了,基础都忘记了,你问一些事情,他总是说框架解决了,而根本不明白
  是怎么回事,所以也提醒大家应该注意平时基础知识的积累,之后对一些问
  题才能游刃有余.
  群里也有些朋友对基础知识很不屑,总说有能力就可以了,
  基础知识考不出来什么.对于这样的观点,我一直不苟同.
  这个只是一点感概罢了. 下面看正题,介绍一个php的Cache类:
  
  All the code here is covered by the PHPGuru license. A short summary is that for any sort of commercial use there is a small one-off licensing fee to pay, and for charity and educational use there is a reduced license fee.
  You can read more about licensing here (where there's also a link to Google Checkout).
  
  贴一下代码吧:下面也有下载地址,其实很简单,重要的是学习

DSC0000.gif DSC0001.gif 代码

<?php
    /**
    * o------------------------------------------------------------------------------o
    * | This package is licensed under the Phpguru license. A quick summary is       |
    * | that for commercial use, there is a small one-time licensing fee to pay. For |
    * | registered charities and educational institutes there is a reduced license   |
    * | fee available. You can read more  at:                                        |
    * |                                                                              |
    * |                  http://www.phpguru.org/static/license.html                  |
    * o------------------------------------------------------------------------------o
    */

/**
* Caching Libraries for PHP5
*
* Handles data and output caching. Defaults to /dev/shm
* (shared memory). All methods are static.
*
* Eg: (output caching)
*
* if (!OutputCache::Start('group', 'unique id', 600)) {
*
*   // ... Output
*
*   OutputCache::End();
* }
*
* Eg: (data caching)
*
* if (!$data = DataCache::Get('group', 'unique id')) {
*
*   $data = time();
*
*   DataCache::Put('group', 'unique id', 10, $data);
* }
*
* echo $data;
*/
    class Cache
    {
        /**
        * Whether caching is enabled
        * @var bool
        */
        public static $enabled = true;
        /**
        * Place to store the cache files
        * @var string可以根据需要修改存储路径,例如当前的cache目录下
        */
        protected static $store = '/dev/shm/';
        
        /**
        * Prefix to use on cache files
        * @var string
        */
        protected static $prefix = 'cache_';
        /**
        * Stores data
        *
        * @param string $group Group to store data under
        * @param string $id    Unique ID of this data
        * @param int    $ttl   How long to cache for (in seconds)
        */
        protected static function write($group, $id, $ttl, $data)
        {
            $filename = self::getFilename($group, $id);
            
            if ($fp = @fopen($filename, 'xb')) {
            
                if (flock($fp, LOCK_EX)) {
                    fwrite($fp, $data);
                }
                fclose($fp);
               
                // Set filemtime
                touch($filename, time() + $ttl);
            }
        }
        
        /**
        * Reads data
        *
        * @param string $group Group to store data under
        * @param string $id    Unique ID of this data
        */
        protected static function read($group, $id)
        {
            $filename = self::getFilename($group, $id);
            
            return file_get_contents($filename);
        }
        
        /**
        * Determines if an entry is cached
        *
        * @param string $group Group to store data under
        * @param string $id    Unique ID of this data
        */
        protected static function isCached($group, $id)
        {
            $filename = self::getFilename($group, $id);
            if (self::$enabled && file_exists($filename) && filemtime($filename) > time()) {
                return true;
            }
            @unlink($filename);
            return false;
        }
        
        /**
        * Builds a filename/path from group, id and
        * store.
        *
        * @param string $group Group to store data under
        * @param string $id    Unique ID of this data
        */
        protected static function getFilename($group, $id)
        {
            $id = md5($id);
            return self::$store . self::$prefix . "{$group}_{$id}";
        }
        
        /**
        * Sets the filename prefix to use
        *
        * @param string $prefix Filename Prefix to use
        */
        public static function setPrefix($prefix)
        {
            self::$prefix = $prefix;
        }
        /**
        * Sets the store for cache files. Defaults to
        * /dev/shm. Must have trailing slash.
        *
        * @param string $store The dir to store the cache data in
        */
        public static function setStore($store)
        {
            self::$store = $store;
        }
    }
   
    /**
    * Output Cache extension of base caching class
    */
    class OutputCache extends Cache
    {
        /**
        * Group of currently being recorded data
        * @var string
        */
        private static $group;
        
        /**
        * ID of currently being recorded data
        * @var string
        */
        private static $id;
        
        /**
        * Ttl of currently being recorded data
        * @var int
        */
        private static $ttl;
        /**
        * Starts caching off. Returns true if cached, and dumps
        * the output. False if not cached and start output buffering.
        *
        * @param  string $group Group to store data under
        * @param  string $id    Unique ID of this data
        * @param  int    $ttl   How long to cache for (in seconds)
        * @return bool          True if cached, false if not
        */
        public static function Start($group, $id, $ttl)
        {
            if (self::isCached($group, $id)) {
                echo self::read($group, $id);
                return true;
            
            } else {
               
                ob_start();
               
                self::$group = $group;
                self::$id    = $id;
                self::$ttl   = $ttl;
               
                return false;
            }
        }
        
        /**
        * Ends caching. Writes data to disk.
        */
        public static function End()
        {
            $data = ob_get_contents();
            ob_end_flush();
            
            self::write(self::$group, self::$id, self::$ttl, $data);
        }
    }
   
    /**
    * Data cache extension of base caching class
    */
    class DataCache extends Cache
    {
   
        /**
        * Retrieves data from the cache
        *
        * @param  string $group Group this data belongs to
        * @param  string $id    Unique ID of the data
        * @return mixed         Either the resulting data, or null
        */
        public static function Get($group, $id)
        {
            if (self::isCached($group, $id)) {
                return unserialize(self::read($group, $id));
            }
            
            return null;
        }
        
        /**
        * Stores data in the cache
        *
        * @param string $group Group this data belongs to
        * @param string $id    Unique ID of the data
        * @param int    $ttl   How long to cache for (in seconds)
        * @param mixed  $data  The data to store
        */
        public static function Put($group, $id, $ttl, $data)
        {
            self::write($group, $id, $ttl, serialize($data));
        }
    }
?>  
  下载地址:http://www.phpguru.org/downloads/Cache/
  顺便说一下,这个网站也不错:http://www.phpguru.org/
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-103131-1-1.html 上篇帖子: PHP学习:文件操作 下篇帖子: 也谈php和net比较
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表