• 日常搜索
  • 百度一下
  • Google
  • 在线工具
  • 搜转载

使用PhpFastCache提升您的网站性能

在本文中,我们将探索 phpFastCache 库,它允许您在 PHP 应用程序中实现缓存。因此,它有助于提高整体网站性能和页面加载时间。

什么是 PhpFastCache?

PhpFastCache 是一个库,它使在 PHP 应用程序中实现缓存变得轻而易举。它是一个易于使用且功能强大的库,提供了多个api来帮助您轻松实现您选择的缓存策略。

不要误以为它只是一个传统的文件系统缓存方案。事实上,PhpFastCache 支持大量的适配器,让您可以从 Memcache、 redismongodb、CouchDB等高性能后端中进行选择。

让我们快速浏览几个最流行的适配器:

  • 文件系统

  • Memcache、Redis 和 APC

  • CouchDB 和 MongoDB

  • Zend 磁盘缓存和 Zend 内存缓存

如果您在上面的列表中没有找到您选择的适配器,您可以轻松开发一个自定义驱动程序,该驱动程序可以插入系统并轻松运行。

除了基本功能之外,PhpFastCache 库还提供了一种事件机制,允许您响应某些预定义的事件。例如,当从缓存中删除某些内容时,您可以捕获此事件并刷新或删除相关数据。

在接下来的部分中,我们将介绍 PhpFastCache的安装和配置,以及一些示例的演示。

安装和配置

在本节中,我们将介绍 PhpFastCache 库的安装和配置。在您的项目中,您可以采用不同的方法来解决这个问题。

如果您只是想轻松地下载 .zip或.tar.gz版本的库,您可以从官方网站获取它。

另一方面,您也可以将其安装为 Composer 包。这应该是首选方式,因为它使将来的维护和升级更容易。如果您尚未安装 Composer,则必须先安装。

安装 Composer 后,让我们继续使用以下命令获取 PhpFastCache 库。

$composer require phpfastcache/phpfastcache

成功完成该命令后,您应该拥有供应商目录,其中包含运行 PhpFastCache 库所需的所有内容。另一方面,如果您缺少 PhpFastCache 库所需的任何库或扩展,Composer 会要求您先安装它们。

您还应该找到如下composer.json所示的文件:

{
    "require": {
        "phpfastcache/phpfastcache": "^6.1"
    }
}

无论您选择哪种方式安装 PhpFastCache 库,唯一需要做的就是在您的应用程序中包含autoload.php 文件以启动。

如果您使用的是基于 Composer 的工作流程, 则autoload.php位于vendor目录下。

// Include composer autoloader
require '{YOUR_APP_PATH}/vendor/autoload.php';

另一方面,如果您下载了.zip或.tar.gz包, 则autoload.php应该在src/autoload.php中可用。

// Include autoloader
require '{YOUR_APP_PATH}/src/autoload.php';

有了这个,你就可以开始缓存并获得惊人的 PhpFastCache 库的好处了。在下一节中,我们将通过几个实际示例演示如何在您的应用程序中使用 PhpFastCache。

示范

我已经提到 PhpFastCache 库在缓存方面支持各种适配器。在本节中,我将演示如何使用文件系统和 Redis 适配器。

使用文件适配器缓存

继续创建具有以下内容的file_cache_example.php文件。我假设您使用的是 Composer 工作流程,因此供应商目录与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文件并导入我们打算使用的命名空间。

// Include composer autoloader
require __DIR__ . '/vendor/autoload.php';

use phpFastCache\CacheManager;

当您使用文件缓存时,您应该提供保存由缓存系统生成的文件的目录路径。这正是我们在以下代码段中配置的内容。

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

当然,我们需要确保缓存目录存在并且可以被 Web 服务器写入。

接下来,我们实例化缓存对象并尝试使用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);

如果缓存中不存在该项目,我们会将其添加到缓存中 60 秒并从缓存中显示它。另一方面,如果它存在于缓存中,我们将直接获取它!

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 缓存适配器模拟相同的示例。

使用 Redis 适配器进行缓存

在我们继续之前,我假设您已经安装了 Redis 服务器并且它在端口 6379 上运行,这是 Redis 的默认端口。

设置好之后,让我们继续创建具有以下内容的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 服务器不是 localhost,您应该更改主机和端口设置以满足您的要求。

继续运行redis_cache_example.php文件,看看它是如何工作的。您还可以通过检查 Redis CLI 中的输出来确认它。

127.0.0.1:6379> KEYS *
1) "welcome_message"

这就是使用 Redis 适配器所需的全部内容。我鼓励您尝试不同的适配器及其选项!

结论

今天,我们介绍了最流行的 PHP 缓存库之一——PhpFastCache。在文章的前半部分,我们讨论了基础知识以及安装和配置。在本文后面,我们通过几个示例来演示我们讨论的概念。


文章目录
  • 什么是 PhpFastCache?
  • 安装和配置
  • 示范
    • 使用文件适配器缓存
    • 使用 Redis 适配器进行缓存
  • 结论