Home > Backend Development > PHP Tutorial > PHP method to operate a class library of Memcache (code)

PHP method to operate a class library of Memcache (code)

不言
Release: 2023-04-05 18:30:02
forward
2249 people have browsed it

The content of this article is about the method (code) of a class library of PHP operating Memcache. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The code is as follows:

<?php
/**
 * Created by PhpStorm.
 * User: alisleepy
 * Date: 2019-03-14 9:42
 * Description: {memcache类}
 */
/**
 * Class Memcacheds
 * 缓存类,主要包含一些基本的操作:set、get、del
 */
class Memcacheds{
    //声明静态成员变量
    private static $m      = null;
    private static $cache  = null;
    private static $server = &#39;127.0.0.1&#39;;    //地址
    private static $port   = &#39;11211&#39;;        //端口

    public function __construct() {
        self::$m = new Memcache();
        self::$m->connect(self::$server, self::$port); //写入缓存地址,port
    }

    //为当前类创建对象
    private static function Men(){
        self::$cache = new Memcacheds();
        return self::$m;
    }

    /*
     * 加入缓存数据
     * @param string $key 获取数据唯一key
     * @param String||Array $value 缓存数据
     * @param $time memcache生存周期(秒)
     */
    public static function set_cache($key,$value,$time){
        self::Men()->set($key,$value,0,$time);
    }

    /*
     * 获取缓存数据
     * @param string $key
     * @return
     */
    public static function get_cache($key){
        return self::Men()->get($key);
    }

    /*
     * 删除相应缓存数据
     * @param string $key
     * @return
     */
    public static function del_cache($key){
        self::Men()->delete($key);
    }

    /*
     * 删除全部缓存数据
     */
    public static function del_all_cache(){
        self::Men()->flush();
    }

    /*
     * 获取服务器统计信息(一般不用)
     */
    public static function get_cache_status(){
        return self::Men()->getStats();
    }
}
Copy after login

The usage example is as follows:

//引入类库
Vendor(&#39;Memcacheds.Memcacheds&#39;);
//实例化(也可以不用实例化,直接类名::静态方法名调用)
$memcached = new \Memcacheds();
//获取缓存
$ticket = $memcached->get_cache(&#39;jsapi_ticket&#39;);
//设置缓存,参数全部必填
$memcached->set_cache(&#39;jsapi_ticket&#39;, $ticket, 7000);
//清除缓存
$memcached->del_cache(&#39;jsapi_ticket&#39;);
Copy after login

The above is the detailed content of PHP method to operate a class library of Memcache (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template