構建自己的PHP框架--構建緩存組件(2)

来源:http://www.cnblogs.com/CraryPrimitiveMan/archive/2016/04/30/5449215.html
-Advertisement-
Play Games

上一篇博客中使用文件實現了緩存組件,這一篇我們就使用Redis來實現一下,剩下的如何使用memcache、mysql等去實現緩存我就不一一去做了。 首先我們需要安裝一下 redis 和 phpredis 庫,phpredis 項目在github上的地址:https://github.com/phpr ...


上一篇博客中使用文件實現了緩存組件,這一篇我們就使用Redis來實現一下,剩下的如何使用memcache、mysql等去實現緩存我就不一一去做了。

首先我們需要安裝一下 redis 和 phpredis 庫,phpredis 項目在github上的地址:https://github.com/phpredis/phpredis 。相應的文檔也在上面。

先在 src/cache 文件夾下創建 RedisCache.php 文件。在寫組件的時候發現我們缺少一個地方去創建一個 Redis 的實例,並且是在創建 cahce 實例之後,返回給Yii::createObject 方法之前。所以我們修改了 src/Sf.php 文件,其 createObject 方法的內容如下:

    public static function createObject($name)
    {
        $config = require(SF_PATH . "/config/$name.php");
        // create instance
        $instance = new $config['class']();
        unset($config['class']);
        // add attributes
        foreach ($config as $key => $value) {
            $instance->$key = $value;
        }
        $instance->init();
        return $instance;
    }

對比之前的代碼,不難發現其實只添加了一行 $instance->init(); ,這樣我們就可以在 init 方法中去創建相應的 Redis 實例,並保存下來。但這樣又會引入一個問題,所有使用 Yii::createObject 創建的實例都必須含有 init 方法(當然你也可以判斷有沒有這個方法)。那我們就來實現一個基礎類 Component ,並規定所有使用 Yii::createObject 創建的實例都集成它,然後再在 Component 中加入 init 方法即可。

為什麼選擇這種做法,而不是使用判斷 init 方法存不存在的方式去解決這個問題,主要是考慮到之後可能還需要對這些類做一些公共的事情,就提前抽出了 Component 類。

Component 類現在很簡單,其內容如下:

<?php
namespace sf\base;

/**
 * Component is the base class for most sf classes.
 * @author Harry Sun <sunguangjun@126.com>
 */
class Component
{
    /**
     * Initializes the component.
     * This method is invoked at the end of the constructor after the object is initialized with the
     * given configuration.
     */
    public function init()
    {
    }
}

之後再定義一下 Redis 緩存的配置如下:

<?php
return [
    'class' => 'sf\cache\RedisCache',
    'redis' => [
        'host' => 'localhost',
        'port' => 6379,
        'database' => 0,
        // 'password' =>'jun',
        // 'options' => [Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP],
    ]
];

其中 password 和 options 是選填,其它是必填。

剩下的就是相關實現,就不一一細說了,代碼如下:

<?php
namespace sf\cache;

use Redis;
use Exception;
use sf\base\Component;

/**
 * CacheInterface
 * @author Harry Sun <sunguangjun@126.com>
 */
class RedisCache extends Component implements CacheInterface
{
    /**
     * @var Redis|array the Redis object or the config of redis
     */
    public $redis;

    public function init()
    {
        if (is_array($this->redis)) {
            extract($this->redis);
            $redis = new Redis();
            $redis->connect($host, $port);
            if (!empty($password)) {
                $redis->auth($password);
            }
            $redis->select($database);
            if (!empty($options)) {
                call_user_func_array([$redis, 'setOption'], $options);
            }
            $this->redis = $redis;
        }
        if (!$this->redis instanceof Redis) {
            throw new Exception('Cache::redis must be either a Redis connection instance.');
        }
    }
    /**
     * Builds a normalized cache key from a given key.
     */
    public function buildKey($key)
    {
        if (!is_string($key)) {
            $key = json_encode($key);
        }
        return md5($key);
    }

    /**
     * Retrieves a value from cache with a specified key.
     */
    public function get($key)
    {
        $key = $this->buildKey($key);
        return $this->redis->get($key);
    }

    /**
     * Checks whether a specified key exists in the cache.
     */
    public function exists($key)
    {
        $key = $this->buildKey($key);
        return $this->redis->exists($key);
    }

    /**
     * Retrieves multiple values from cache with the specified keys.
     */
    public function mget($keys)
    {
        for ($index = 0; $index < count($keys); $index++) {
            $keys[$index] = $this->buildKey($keys[$index]);
        }

        return $this->redis->mGet($keys);
    }

    /**
     * Stores a value identified by a key into cache.
     */
    public function set($key, $value, $duration = 0)
    {
        $key = $this->buildKey($key);
        if ($duration !== 0) {
            $expire = (int) $duration * 1000;
            return $this->redis->set($key, $value, $expire);
        } else {
            return $this->redis->set($key, $value);
        }
    }

    /**
     * Stores multiple items in cache. Each item contains a value identified by a key.
     */
    public function mset($items, $duration = 0)
    {
        $failedKeys = [];
        foreach ($items as $key => $value) {
            if ($this->set($key, $value, $duration) === false) {
                $failedKeys[] = $key;
            }
        }

        return $failedKeys;
    }

    /**
     * Stores a value identified by a key into cache if the cache does not contain this key.
     */
    public function add($key, $value, $duration = 0)
    {
        if (!$this->exists($key)) {
            return $this->set($key, $value, $duration);
        } else {
            return false;
        }
    }

    /**
     * Stores multiple items in cache. Each item contains a value identified by a key.
     */
    public function madd($items, $duration = 0)
    {
        $failedKeys = [];
        foreach ($items as $key => $value) {
            if ($this->add($key, $value, $duration) === false) {
                $failedKeys[] = $key;
            }
        }

        return $failedKeys;
    }

    /**
     * Deletes a value with the specified key from cache
     */
    public function delete($key)
    {
        $key = $this->buildKey($key);
        return $this->redis->delete($key);
    }

    /**
     * Deletes all values from cache.
     */
    public function flush()
    {
        return $this->redis->flushDb();
    }
}

訪問 http://localhost/simple-framework/public/index.php?r=site/cache 路徑,得到結果如下:

我就是測試一下緩存組件

這樣我們完成了使用 Redis 的緩存組件。

好了,今天就先到這裡。項目內容和博客內容也都會放到Github上,歡迎大家提建議。

code:https://github.com/CraryPrimitiveMan/simple-framework/tree/0.9

blog project:https://github.com/CraryPrimitiveMan/create-your-own-php-framework


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 初學java,面對著這個static修飾符,愣是琢磨了兩天時間,還在今天琢磨透了,現在將悟到的東西記錄下來: 1、static修飾符表示靜態修飾符,其所修飾的內容(變數、方法、代碼塊暫時學到這三種)統稱為靜態內容(靜態變數、靜態方法、靜態代碼塊) 2、靜態內容是與類相關的內容。解釋:靜態變數在類載入 ...
  • 1、加入相應依賴包 junit4-4.7.jar 以及spring相關jar包 2、在測試代碼的源碼包中如 src/test/java 新建一個抽象類如下 3、測試 可以看到自動去載入相關的配置文件,最終顯示添加成功 ...
  • autorelease 自動釋放池 autorelease是一種支持引用計數的記憶體管理方式,只要給對象發送一條autorelease消息,會將對象放到一個自動釋放池中,當自動釋放池被銷毀時,會對池子裡面的所有對象做一次release操作 優點:不用再關心對象釋放的時間,不用再關心什麼時候調用rele ...
  • 回顧一下處理連連看消除邏輯(演算法實現) 相同圖片能夠消除 在同一行或者同一列無障礙物可消除 一個拐點可消除 兩個拐點可消除 這一部分和之前沒有多大變動,加了一個數組輸入輸出存儲,eclipse自動報錯加上去的。(74-76行) 到這一步已經實現任意兩個圖形相消除,接下來是——兩個相同圖形的消除。 ...
  • 這兩周正在寫畢業設計,我做的是一個問答網站。先介紹一下這個網站:這是一個關於大學生線上問答的網站,類似知乎和百度知道,不過功能沒有人家多,畢竟這個網站我一個人在做。網站部署在阿裡雲,網站包括API,Web,IOS,三大模塊,現在沒有找到人幫忙寫安卓,唉... 網站API已經寫完了,Web端正在完善開 ...
  • 十進位 八進位 十六進位 二進位 字元 ASCII名稱 0 0 0 0000 0000 ^@ NUL 1 1 1 0000 0001 ^A SOH 2 2 2 0000 0010 ^B STX 3 3 3 0000 0011 ^C ETX 4 4 4 0000 0100 ^D EOT 5 5 5 0... ...
  • 一,介紹 本文討論JAVA多線程中,使用 thread.suspend()方法暫停線程,使用 thread.resume()恢復暫停的線程 的特點。 先介紹二個關於線程的基本知識: ①線程的執行體是run()方法裡面的每一條語句,main線程執行的則是main()方法裡面的語句。 ②Thread.s ...
  • 問題描述: 今天CZY又找到了三個妹子,有著收藏愛好的他想要找三個地方將妹子們藏起來,將一片空地抽象成一個R行C列的表格,CZY要選出3個單元格。但要滿足如下的兩個條件: (1)任意兩個單元格都不在同一行。 (2)任意兩個單元格都不在同一列。 選取格子存在一個花費,而這個花費是三個格子兩兩之間曼哈頓 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...