- Boost Your Website Performance With PhpFastCache
- Originally written by Sajal Soni
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: lsvih
- Proofreader: Eat dirt small 2 tablespoons
In this article, you’ll explore the PhpFastCache library to implement caching capabilities for your PHP applications. The caching function can improve the overall performance of the website and page loading speed.
What is PhpFastCache?
PhpFastCache is a library that makes it easy to implement caching in PHP applications. It is powerful and easy to use, providing apis to implement caching strategies painlessly.
PhpFastCache is not a pure traditional file system cache. It supports a wide variety of Files Adapters, allowing you to choose from high-performance back-end services like Memcache, Redis, MongoDB, CouchDB, etc.
Let’s start with an overview of the most popular adapters:
- The file system
- Memcache, Redis and APC
- CouchDB and mongo
- Zend Disk Cache and Zend Memory Cache
If the file adapter you are using is not listed above, you can simply develop a custom driver, plug it into your system, and run as efficiently as possible.
In addition to basic functionality, PhpFastCache provides an event mechanism that lets you respond to predefined events. For example, when something is deleted from the cache, you can receive the event and refresh or delete the associated data.
In the following sections, we’ll walk through some examples to see how to install and configure PhpFastCache.
Installation and Configuration
In this section, you’ll learn how to install and configure PhpFastCache. Here are a few ways to integrate it into a project.
If you can’t be bothered, just download the.zip or.tar.gz files of the library, which can be downloaded directly from the official website.
Or you can install it as a Composer package. This is better because it is easier to maintain and upgrade later. If you haven’t already installed Composer, you need to install it first.
Once you have Composer installed, you can download PhpFastCache with the following command:
$composer require phpfastcache/phpfastcache
Copy the code
When the command is done, you’ll get a vendor directory that contains all the files you need for PhpFastCache. In addition, if you are missing a PhpFastCache dependency library or plugin, Composer will remind you to install the dependency first.
You need to find the composer. Json file, which looks something like this:
{
"require": {
"phpfastcache/phpfastcache": "^ 6.1"}}Copy the code
No matter how you install PhpFastCache, include autoload.php in your application.
If you are using a Composer based workflow, the autoload.php file will be in the vendor directory.
// Include composer autoloader
require '{YOUR_APP_PATH}/vendor/autoload.php';
Copy the code
Alternatively, if you downloaded.zip and.tar.gz directly, the autoload.php path will be SRC /autoload.php.
// Include autoloader
require '{YOUR_APP_PATH}/src/autoload.php';
Copy the code
Once you’ve done that, you’re ready to start caching and enjoy the benefits of PhpFastCache. In the next section, we will use a simple example to show you how to use PhpFastCache in your application.
The sample
As I mentioned earlier, PhpFastCache supports multiple file adapters for caching. In this section, I’ll use two file adapters, file systems and Redis, as examples.
Use a file adapter for caching
Create the file_cache_example.php file and write the following code. I’m assuming you’re using Composer Workflow, so the vendor directory will be at the same level as the file_cache_example.php file. If you are manually installing PhpFastCache, you will need to modify the file structure as required.
/** * 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!
";
echo "The value of welcome_message:" . $CachedString->get();
}
else
{
// The cached entry exists
echo "Already in cache!
";
echo "The value of welcome_message:" . $CachedString->get();
}
Copy the code
Now, let’s understand the code piece by piece. We will import the autoload.php file and then import the namespace we want to use:
// Include composer autoloader
require __DIR__ . '/vendor/autoload.php';
use phpFastCache\CacheManager;
Copy the code
When you use file caching, it is best to provide a directory path to store files generated by the caching system. The following code does just that:
// Init default configuration for "files" adapter
CacheManager::setDefaultConfig([
"path"= >__DIR__ . "/cache"
]);
Copy the code
Of course, you need to make sure that the cache directory exists and that the Web Server has write permission.
Next, we instantiate the cache object and load the corresponding cache object with 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);
Copy the code
If the object does not exist in the cache, it is added to the cache with an expiration time of 60 seconds, and it is read and displayed from the cache. If it exists in the cache, get it directly:
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!
";
echo "The value of welcome_message:" . $CachedString->get();
}
else
{
// The cached entry exists
echo "Already in cache!
";
echo "The value of welcome_message:" . $CachedString->get();
}
Copy the code
Very easy to learn, right? You can try running the program yourself to see the results.
When you first run this program, you should see the following output:
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!
Copy the code
When it runs again, the output will look like this:
Already in cache!
The value of welcome_message: This website uses PhpFastCache!
Copy the code
File system caching is now a no-brainer. In the next section, we will emulate this example to implement caching using Redis Adapter.
Use Redis Adapter for caching
Assume you have the Redis service installed and running on the default port 6379 before reading this section.
The following configuration is performed. Create the redis_cache_example.php file and write the following code:
/** * 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!
";
echo "The value of welcome_message:" . $CachedString->get();
}
else
{
// The cached entry exists
echo "Already in cache!
";
echo "The value of welcome_message:" . $CachedString->get();
}
Copy the code
As you can see, this file is basically the same as before, except for the configuration section that initializes the Redis adapter.
// Init default configuration for "redis" adapter
CacheManager::setDefaultConfig([
"host"= >'127.0.0.1'."port"= >6379
]);
Copy the code
Of course, if you want to run the Redis service on a non-native machine, you will need to modify the host and port Settings as required.
To see how it works, run the redis_cache_example.php file. You can also view the output in Redis CLI.
127.0.0.1:6379 > KEYS * 1)"welcome_message"
Copy the code
That’s all for using the Redis adapter. Try out different adapters and configurations!
conclusion
This article briefly introduces PhpFastCache, one of the most popular libraries in PHP. In the first half of the article, we discussed the basics as well as installation and configuration. In the second half of the article, we demonstrate the concepts mentioned above in detail through several examples.
Hope you enjoy this article and integrate PhpFastCache into your upcoming projects. Questions and discussions are welcome!
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.