[譯] 使用 PhpFastCache 提高網站性能

本文將與你一同探索 PhpFastCache 庫,來爲你的 PHP 應用實現緩存功能。經過緩存功能,可以提高網站的總體性能與頁面加載速度。php

什麼是 PhpFastCache?

PhpFastCache 是一個能讓你輕鬆在 PHP 應用中實現緩存功能的庫。它的功能強大,且簡單易用,提供了一些 API 以無痛實現緩存策略。前端

PhpFastCache 不是一個純粹的傳統文件系統式緩存。它支持各類各樣的文件適配器(Files Adapter),可讓你選擇 Memcache、Redis、MongoDB、CouchDB 等高性能的後端服務。android

讓咱們先總覽一遍最流行的適配器:ios

  • 文件系統
  • Memcache、Redis 和 APC
  • CouchDB 和 MongoDB
  • Zend Disk Cache 和 Zend Memory Cache

若是你用的文件適配器不在上面的列表中,也能夠簡單地開發一個自定義驅動,插入到系統中,一樣也能高效地運行。git

除了基本功能外,PhpFastCache 還提供了事件機制,可讓你對預約義好的事件進行響應。例如,當某個事物從緩存中被刪除時,你能夠接收到這個事件,並去刷新或刪除相關的數據。github

在下面的章節中,咱們將經過一些示例來了解如何安裝及配置 PhpFastCache。web

安裝與配置

在本節中,咱們將瞭解如何安裝及配置 PhpFastCache。下面是幾種將它集成進項目的方法。redis

若是你嫌麻煩,僅準備下載這個庫的 .zip 或者 .tar.gz 文件,能夠去官方網站直接下載。json

或者你也能夠用 Composer 包的方式來安裝它。這種方式更好,由於在以後的維護和升級時會更方便。若是你尚未安裝 Composer,須要先去安裝它。後端

當你安裝好 Composer 以後,能夠用如下命令下載 PhpFastCache:

$composer require phpfastcache/phpfastcache
複製代碼

命令完成後,你會獲得一個 vendor 目錄,在此目錄中包括了所有 PhpFastCache 所需的文件。另外,若是你缺失了 PhpFastCache 依賴的庫或插件,Composer 會提醒你先去安裝依賴。

你須要找到 composer.json 文件,它相似於下面這樣:

{
    "require": {
        "phpfastcache/phpfastcache": "^6.1"
    }
}
複製代碼

不管你經過什麼方式來安裝的 PhpFastCache,都要在應用中 include autoload.php 文件。

若是你用的是基於 Composer 的工做流,autoload.php 文件會在 vendor 目錄中。

// Include composer autoloader
require '{YOUR_APP_PATH}/vendor/autoload.php';
複製代碼

另外,若是你是直接下載的 .zip.tar.gzautoload.php 的路徑會在 src/autoload.php

// Include autoloader
require '{YOUR_APP_PATH}/src/autoload.php';
複製代碼

只要完成上面的操做,就能開始進行緩存,享受 PhpFastCache 帶來的好處了。在下一章節中,咱們將以一個簡單的示例來介紹如何在你的應用中使用 PhpFastCache。

示例

前面我提到過,PhpFastCache 支持多種文件適配器進行緩存。在本節中,我會以文件系統和 Redis 這兩種文件適配器爲例進行介紹。

使用文件適配器進行緩存

建立 file_cache_example.php 文件並寫入下面的代碼。在此我假設你使用的是 Composer workflow,所以 vendor 目錄會與 file_cache_example.php 文件同級。若是你是手動安裝的 PhpFastCache,須要根據實際狀況修改文件結構。

<?php
/** * file_cache_example.php * * Demonstrates usage of phpFastCache with "file system" adapter */
 
// Include composer autoloader
require __DIR__ . '/vendor/autoload.php';
 
use phpFastCache\CacheManager;
 
// Init default configuration for "files" adapter
CacheManager::setDefaultConfig([
  "path" => __DIR__ . "/cache"
]);
 
// Get instance of files cache
$objFilesCache = CacheManager::getInstance('files');
 
$key = "welcome_message";
 
// Try to fetch cached item with "welcome_message" key
$CachedString = $objFilesCache->getItem($key);
 
if (is_null($CachedString->get()))
{
    // The cached entry doesn't exist
    $numberOfSeconds = 60;
    $CachedString->set("This website uses PhpFastCache!")->expiresAfter($numberOfSeconds);
    $objFilesCache->save($CachedString);
 
    echo "Not in cache yet, we set it in cache and try to get it from cache!</br>";
    echo "The value of welcome_message:" . $CachedString->get();
}
else
{
    // The cached entry exists
    echo "Already in cache!</br>";
    echo "The value of welcome_message:" . $CachedString->get();
}
複製代碼

如今,咱們一塊一塊地來理解代碼。首先看到的是將 autoload.php 文件引入,而後導入要用到的 namespace:

// Include composer autoloader
require __DIR__ . '/vendor/autoload.php';
 
use phpFastCache\CacheManager;
複製代碼

當你使用文件緩存的時候,最好提供一個目錄路徑來存放緩存系統生成的文件。下面的代碼就是作的這件事:

// Init default configuration for "files" adapter
CacheManager::setDefaultConfig([
  "path" => __DIR__ . "/cache"
]);
複製代碼

固然,你須要確保 cache 目錄存在且 web server 有寫入權限。

接下來,咱們將緩存對象實例化,用 welcome_message 加載對應的緩存對象。

// Get instance of files cache
$objFilesCache = CacheManager::getInstance('files');
 
$key = "welcome_message";
 
// Try to fetch cached item with "welcome_message" key
$CachedString = $objFilesCache->getItem($key);
複製代碼

若是緩存中不存在此對象,就將它以 60s 過時時間加入緩存,並從緩存中讀取與展現它。若是它存在於緩存中,則直接獲取:

if (is_null($CachedString->get()))
{
    // The cached entry doesn't exist
    $numberOfSeconds = 60;
    $CachedString->set("This website uses PhpFastCache!")->expiresAfter($numberOfSeconds);
    $objFilesCache->save($CachedString);
 
    echo "Not in cache yet, we set it in cache and try to get it from cache!</br>";
    echo "The value of welcome_message:" . $CachedString->get();
}
else
{
    // The cached entry exists
    echo "Already in cache!</br>";
    echo "The value of welcome_message:" . $CachedString->get();
}
複製代碼

很是容易上手對吧!你能夠試着本身去運行一下這個程序來查看結果。

當你第一次運行這個程序時,應該會看到如下輸出:

Not in cache yet, we set it in cache and try to get it from cache!
The value of welcome_message: This website uses PhpFastCache!
複製代碼

以後再運行的時候,輸出會是這樣:

Already in cache!
The value of welcome_message: This website uses PhpFastCache!
複製代碼

如今就能隨手實現文件系統緩存了。在下一章節中,咱們將模仿這個例子來使用 Redis Adapter 實現緩存。

使用 Redis Adapter 進行緩存

假定你在閱讀本節前已經安裝好了 Redis 服務,並讓它運行在 6379 默認端口上。

下面進行配置。建立 redis_cache_example.php 文件並寫入如下代碼:

<?php
/** * redis_cache_example.php * * Demonstrates usage of phpFastCache with "redis" adapter * * Make sure php-redis extension is installed along with Redis server. */
 
// Include composer autoloader
require __DIR__ . '/vendor/autoload.php';
 
use phpFastCache\CacheManager;
 
// Init default configuration for "redis" adapter
CacheManager::setDefaultConfig([
  "host" => '127.0.0.1',
  "port" => 6379
]);
 
// Get instance of files cache
$objRedisCache = CacheManager::getInstance('redis');
 
$key = "welcome_message";
 
// Try to fetch cached item with "welcome_message" key
$CachedString = $objRedisCache->getItem($key);
 
if (is_null($CachedString->get()))
{
    // The cached entry doesn't exist
    $numberOfSeconds = 60;
    $CachedString->set("This website uses PhpFastCache!")->expiresAfter($numberOfSeconds);
    $objRedisCache->save($CachedString);
 
    echo "Not in cache yet, we set it in cache and try to get it from cache!</br>";
    echo "The value of welcome_message:" . $CachedString->get();
}
else
{
    // The cached entry exists
    echo "Already in cache!</br>";
    echo "The value of welcome_message:" . $CachedString->get();
}
複製代碼

如你所見,除了初始化 Redis 適配器的配置一段以外,這個文件與以前基本同樣。

// Init default configuration for "redis" adapter
CacheManager::setDefaultConfig([
  "host" => '127.0.0.1',
  "port" => 6379
]);
複製代碼

固然若是你要在非本機運行 Redis 服務,須要根據需求修改 host 與 port 的設置。

運行 redis_cache_example.php 文件來查看它的工做原理。你也能夠在 Redis CLI 中查看輸出。

127.0.0.1:6379> KEYS *
1) "welcome_message"
複製代碼

以上就是使用 Redis 適配器的所有內容。你能夠去多試試其它不一樣的適配器和配置!

總結

本文簡單介紹了 PhpFastCache 這個 PHP 中很是熱門的庫。在文章前半部分,咱們討論了它的基本知識以及安裝和配置。在文章後半部分,咱們經過幾個例子來詳細演示了前面提到的概念。

但願你喜歡這篇文章,並將 PhpFastCache 集成到你即將開發的項目中。隨時歡迎提問和討論!

若是發現譯文存在錯誤或其餘須要改進的地方,歡迎到 掘金翻譯計劃 對譯文進行修改並 PR,也可得到相應獎勵積分。文章開頭的 本文永久連接 即爲本文在 GitHub 上的 MarkDown 連接。


掘金翻譯計劃 是一個翻譯優質互聯網技術文章的社區,文章來源爲 掘金 上的英文分享文章。內容覆蓋 AndroidiOS前端後端區塊鏈產品設計人工智能等領域,想要查看更多優質譯文請持續關注 掘金翻譯計劃官方微博知乎專欄

相關文章
相關標籤/搜索