- Saved searches
- Use saved searches to filter your results more quickly
- License
- cosenary/Simple-PHP-Cache
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.markdown
- About
- Quick Tip: How to Cache Data in PHP
- What is Caching?
- Output Buffering
- Caching Functions
- apc_store()
- memcache_set()
- xcache_set()
- Caching with a Database
- Conclusion
- Share This Article
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A light, simple but powerful PHP5 Cache Class which uses the filesystem for caching.
License
cosenary/Simple-PHP-Cache
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.markdown
A light, simple but powerful PHP5 Cache Class which uses the filesystem for caching.
Your feedback is always welcome.
Basically the caching class stores its data in files in the JSON format. These files will be created if you store data under a Cache name.
If you set a new Cache name with setCache() , a new cache file will be generated. The Cache will store all further data in the new file. The Setter method allows you to switch between the different Cache files.
It’s not much trouble to setup the Cache.
First create a writable directory cache/ and include the Cache class:
require_once 'cache.class.php'; // setup 'default' cache $c = new Cache(); ?>
Now we’ve setup the Cache instance and can start caching!
// store a string $c->store('hello', 'Hello World!'); // generate a new cache file with the name 'newcache' $c->setCache('newcache'); // store an array $c->store('movies', array( 'description' => 'Movies on TV', 'action' => array( 'Tropic Thunder', 'Bad Boys', 'Crank' ) )); // get cached data by its key $result = $c->retrieve('movies'); // display the cached array echo ''
; print_r($result); echo ''
; // grab array entry $description = $result['description']; // switch back to the first cache $c->setCache('mycache'); // update entry by simply overwriting an existing key $c->store('hello', 'Hello everybody out there!'); // erase entry by its key $c->erase('hello'); ?>
You can also make use of the Method Chaining feature, introduced in PHP5.
So you can do something like that:
$c->setCache('mycache') // generate new file ->store('hello', 'world') // store data string ->retrieve('hello'); // retrieve cached data ?>
string gives you the basic setup.
It's the name of your Cache (standard Cache name is 'default'):
array allows you to define multiple optional parameters:
new Cache(array( 'name' => 'YOUR-CACHE-NAME', 'path' => 'cache/', 'extension' => '.cache' ));
If you don't define a Cache name with the constructor or the setCache() method, it'll be 'default'.
- The key value defines a tag with which the cached data will be associated.
- The data value can be any type of object (will be serialized).
- The expiration value allows you to define an expiration time.
To change data you can overwrite it by using the same key identifier.
Beside the data, the Cache will also store a timestamp.
A sample Cache entry looks like this:
< "christmas": < "time": 1324664631, "expire": 28000, "data": "s:29:"A great time to bake cookies.";" // serialized > >
Get particular cached data by its key.
To retrieve the timestamp of a key, set the second parameter to true .
This allows you retrieve all the cached data at once. You get the meta data by setting the $meta argument to true .
For erasing cached data are these three methods available:
- erase($key) Erases a single entry by its key.
- eraseAll() Erases all entries from the Cache file.
- eraseExpired() Erases all expired entries.
// returns the count of erased entries echo $c->eraseExpired() . ' expired items erased!'; ?>
Check whether any data is associated with the given key.
Returns true or false .
If you want to switch to another Cache or create a new one, then use this method to set a new Cache name.
The path to the Cache folder must end with a backslash: my_path_to_the_cache_folder/
The method returns the path to your current Cache file (the Cache name is always sh1 encoded):
cache/7505d64a54e061b7acd54ccd58b49dc43500b635.cache
If you've done one, please let me know.
Upcoming: Simple Cache 2.0
Implementation of an internal "soft cache", hash-sum handling and the switch to serialization. Thanks @dariushha for his contribution!
Simple Cache 1.6 - 04/01/2014
Simple Cache 1.5 - 01/01/2014
Simple Cache 1.4 - 08/09/2013
- bug Fixed loading file twice in store() method.
- bug Fixed retrieve() method - made it fail safe (thanks @dariushha).
Simple Cache 1.3 - 28/02/2013
- update Updated docs for the added retrieveAll() method.
- feature Added retrieveAll() method (thanks @rpnzl).
Simple Cache 1.2 - 09/05/2012
- update Formatted code
- bug Fixed isCached() method so that it works as expected (thanks @TigerWolf).
Simple Cache 1.1 - 01/01/2012
- change The extension config has to start now with a dot.
- feature Added expiration handling to the store() method
- feature Added the methods eraseExpired() and eraseAll()
- feature Added method to make sure that a writable directory exists
Simple Cache 1.0 - 29/12/2011
Simple Cache 0.9 - 25/12/2011
- update Added Quick Start guide to the documentation
- feature Added Method Chaining possibility
- bug Fixed constructor configuration string/array handling
Simple Cache 0.8 - 24/12/2011
- release First internal beta version (tested)
- feature Added Setter and Getter methods
- update Detailed documentation
Simple Cache 0.5 - 22/12/2011
Copyright (c) 2011-2013 - Programmed by Christian Metz / @cosenary
Released under the BSD License.
About
A light, simple but powerful PHP5 Cache Class which uses the filesystem for caching.
Quick Tip: How to Cache Data in PHP
It’s crucial to focus on performance when developing PHP apps. Web apps can have thousands or even millions of users, which can lead to slow performance and availability issues. Caching is invaluable in this respect, as it can help avoid performance pitfalls.
What is Caching?
Caching is a way to store frequently accessed data in a temporary storage location to reduce the number of times the data needs to be retrieved from its original storage location. This can greatly improve the performance of a website or application, as accessing data from cache is generally much faster than accessing it from its source.
PHP provides several ways to implement caching. Let’s have a look at each of them.
Output Buffering
Output buffering is a technique in PHP that allows us to store the output of a PHP script in a buffer, rather than sending it directly to the browser. This allows us to modify the output or perform other actions on it before it’s displayed to the user.
To start an output buffer, we can use the ob_start() function. This function will turn output buffering on and begin capturing all output sent by the script. The output can then be stored in a variable using the ob_get_contents() function. Finally, the output buffer can be ended and the output can be sent to the browser using the ob_end_flush() function, or it can be discarded using the ob_end_clean() function.
Here’s an example of how output buffering works:
ob_start(); // Start the output buffer echo 'This output will be stored in the buffer'; $output = ob_get_contents(); // Get the contents of the output buffer ob_end_clean(); // End the output buffer and discard the contents echo 'This output will be sent to the browser';
In this particular example, the string 'This output will be sent to the browser' will be echoed only once, since we’re discarding the contents of the output buffer that contains the first echo instruction.
Output buffering can be used as cache, as it allows us to store the output of a PHP script in memory, rather than generating it every time the script is accessed.
Caching Functions
PHP provides several functions specifically for caching data, including apc_store() , memcache_set() , and xcache_set() . These functions can be used to store data in memory, which can be accessed much faster than data stored on a hard drive.
apc_store()
The apc_store() function is part of the Alternative PHP Cache (APC) extension, which provides an opcode cache for PHP. (Opcode cache is a performance optimization technique for PHP that caches the compiled bytecode of PHP scripts in memory, rather than re-parsing and re-compiling the source code on each request.) It stores a value in the APC cache with a specified key and expiration time.
Here’s an example of how to use the apc_store() function to cache a value in memory:
$value = 'This is the value to cache'; // Store the value in cache for one hour apc_store('cache_key', $value, 3600);
To retrieve the cached value, we can use the apc_fetch() function:
$cachedValue = apc_fetch('cache_key'); if ($cachedValue) // Use the cached value echo $cachedValue; > else // Generate the value and store it in cache $value = 'This is the value to cache'; apc_store('cache_key', $value, 3600); echo $value; >
More information on apc_store() can be found here.
memcache_set()
The memcache_set() function is part of the Memcache extension, which allows you to use a Memcache server as a cache for PHP. It stores a value in the Memcache server with a specified key and expiration time.
More information on memcache_set() can be found here.
xcache_set()
The xcache_set() function is part of the XCache extension, which provides a PHP opcode cache and data cache. It stores a value in the XCache cache with a specified key and expiration time.
More information on xcache_set() can be found here.
Caching with a Database
Another option for caching in PHP is to use a database to store cached data. This may seem counterintuitive, as the primary goal of caching is to reduce the number of database accesses and improve performance. However, there are some cases where caching data in a database might be useful.
One such case is if you need to cache large amounts of data that might not fit in memory. Additionally, caching data in a database can be useful if you need to access the cached data from multiple servers, as it allows for easy sharing of cached data between servers.
To cache data in a database, you can use a table with at least two columns: one for the cache key, and one for the cached data. You can then use a SELECT query to check if the cache key exists in the table, and an INSERT or UPDATE query to store the data in the table.
Here’s an example of how to cache data in a MySQL database:
$db = new mysqli('localhost', 'username', 'password', 'database'); $cacheKey = 'cache_key'; $cachedValue = 'This is the value to cache'; // Check if the cache key exists in the table $result = $db->query("SELECT * FROM cache WHERE cache_key = '$cacheKey'"); if ($result->num_rows > 0) // Update the cached value $db->query("UPDATE cache SET value = '$cachedValue' WHERE cache_key = '$cacheKey'"); > else // Insert a new cache row $db->query("INSERT INTO cache (cache_key, value) VALUES ('$cacheKey', '$cachedValue')"); > // Retrieve the cached value $result = $db->query("SELECT * FROM cache WHERE cache_key = '$cacheKey'"); $row = $result->fetch_assoc(); $cachedValue = $row['value']; echo $cachedValue;
This example demonstrates how to check if a cache key exists in the cache table, and if it does, how to update the cached value. If the cache key doesn’t exist, a new row is inserted into the table with the cache key and value. The cached value is then retrieved from the table and displayed to the user.
Conclusion
Caching is a very powerful technique for improving the performance of a PHP website or application. PHP provides several options for implementing caching, including output buffering, caching functions, and caching with a database. By storing frequently accessed data in a temporary location, we can reduce the number of times the data needs to be retrieved from its source and improve the overall speed and performance of a site.
Share This Article
Cláudio Ribeiro is a software developer, traveler, and writer from Lisbon. He's the author of the book An IDE Called Vim. When he is not developing some cool feature at Kununu he is probably backpacking somewhere in the world or messing with some obscure framework.