Using Memcached for PHP Data Caching in ServBay
ServBay, as a powerful local web development environment, comes pre-installed with a high-performance Memcached package (Memcached server) and the corresponding PHP extension. This setup makes it easy for developers to implement efficient data caching in PHP applications, dramatically improving application performance.
This article provides a step-by-step guide on how to verify and utilize Memcached and its PHP extension within ServBay.
Introduction to Memcached
Memcached is a high-performance, distributed memory object caching system. By temporarily storing data in memory (such as database query results, API responses, page fragments, etc.), it minimizes the number of backend data store accesses (like databases), thereby accelerating the response speed and throughput of dynamic web applications.
Main Features
- High Performance: Data is stored in memory, resulting in extremely fast read/write speeds.
- Distributed Architecture: Supports building distributed cache pools across multiple servers, making it highly scalable.
- Simple and Easy to Use: Simple protocol, robust client library support, and easy integration.
- Reduced Database Load: Effectively lowers database query pressure, especially in high-concurrency scenarios.
Difference Between memcache
and memcached
PHP Extensions
In PHP, there are two commonly used extensions for connecting to Memcached servers: memcache
and memcached
. Although they have similar names, they are distinct extensions offering different APIs and features:
memcache
Extension:- An older PHP extension.
- Primarily provides procedural APIs (such as
memcache_connect()
,memcache_set()
, etc.). - More basic functionality, lacking some advanced features like consistent hashing (some client libraries may implement these).
memcached
Extension:- A more recent PHP extension (powered by the libmemcached library).
- Offers an object-oriented API via the
Memcached
class. - Supports advanced features like consistent hashing, binary protocol, SASL authentication, and more flexible serialization options.
- Generally, the
memcached
extension is recommended because it's more feature-rich and actively maintained.
ServBay provides and recommends using the more versatile memcached
PHP extension by default.
Memcached Package and PHP Extension in ServBay
ServBay not only integrates the Memcached server as a manageable package, but also pre-installs and enables the memcached
PHP extension by default for all integrated PHP versions.
This means that, in most cases, once you install ServBay, both the Memcached server and the PHP extension are ready to use—no need for extra compilation or PHP configuration.
Checking Memcached Package Status:
You can find the Memcached
package in ServBay's main interface or the package management interface and verify that its status is “Running.” If it isn’t, try starting it.
Verifying the memcached
PHP Extension is Loaded:
To confirm whether the memcached
extension is loaded for a specific PHP version, the simplest method is to use the phpinfo()
function:
In ServBay’s website root directory (default is
/Applications/ServBay/www
), create a new PHP file, e.g.,info.php
.Add the following content to the file:
php<?php phpinfo(); ?>
1
2
3Access this file via your ServBay-configured local site (for example, if your site domain is
servbay.demo
, visithttp://servbay.demo/info.php
).On the opened
phpinfo
page, search for "memcached." If you see a section named "memcached" with configuration info and version number, the extension is loaded and available.
Using Memcached in PHP Code
Once you’ve confirmed that the Memcached server is running and the memcached
PHP extension is loaded, you can use the Memcached
class in your PHP application to connect to the server and perform caching operations.
By default, the Memcached server runs on localhost
at port 11211
.
Example Code
Below is a simple PHP code example that demonstrates how to use the Memcached
class to connect to the local Memcached server, store, and retrieve data:
Save the following code as a PHP file in your ServBay site directory (for example, /Applications/ServBay/www/memcached_test.php
):
<?php
// Memcached server information
$memcached_host = 'localhost';
$memcached_port = 11211;
// Create Memcached client instance
$memcached = new Memcached();
// Add Memcached server to client connection pool
// addServer() returns a boolean indicating if it was added to the list, not if the connection was successful
if (!$memcached->addServer($memcached_host, $memcached_port)) {
// Note: If addServer fails, it's usually a configuration issue, not a server connectivity issue
die("Unable to add Memcached server to client connection list. Please check host and port configuration.");
}
// Try fetching a non-existent key to test the connection (optional, but recommended)
// get() returns false or an empty array if the key doesn't exist or connection fails
// Memcached::getResultCode() provides more detailed status codes
$test_key = 'servbay_memcached_connection_test';
$memcached->get($test_key); // Try to get a non-existent key
$result_code = $memcached->getResultCode();
if ($result_code !== Memcached::RES_NOTFOUND && $result_code !== Memcached::RES_SUCCESS) {
// If not RES_NOTFOUND or RES_SUCCESS, there might be a connection issue
// Note: RES_SUCCESS may be returned for empty values
// More rigorous connection checks may require additional logic or specific client behavior
// For local development, if addServer succeeds and following operations don't throw errors, the connection is likely fine
echo "Note: There may be an issue connecting to the Memcached server. Result Code: " . $result_code . "<br>";
// In real applications, more detailed error handling may be required
} else {
echo "Successfully connected to Memcached server ({$memcached_host}:{$memcached_port}).<br>";
}
// --- Cache operation examples ---
// Data to cache
$key = 'user_profile_1234';
$data = [
'id' => 1234,
'username' => 'servbay-demo',
'email' => '[email protected]',
'status' => 'active'
];
$expiration = 3600; // Cache expiration time in seconds (1 hour)
// Set cache data
// set() returns a boolean indicating if the operation is successful
if ($memcached->set($key, $data, $expiration)) {
echo "Data successfully cached in Memcached with key '{$key}', expiration: {$expiration} seconds.<br>";
} else {
echo "Failed to cache data!<br>";
// You can use $memcached->getResultCode() to get the failure reason
echo "Result Code: " . $memcached->getResultCode() . "<br>";
}
// Attempt to retrieve data from the cache
echo "Attempting to retrieve data from cache...<br>";
$cachedData = $memcached->get($key);
if ($cachedData !== false) { // Memcached::get() returns false if cache miss or error occurs
echo "Successfully retrieved data from cache:<br>";
echo "<pre>";
print_r($cachedData);
echo "</pre>";
} else {
echo "Cache miss or retrieval failed for key '{$key}'.<br>";
echo "Result Code: " . $memcached->getResultCode() . "<br>";
}
// Demonstrating cache expiration scenario (assuming time has elapsed)
// You would typically check if $cachedData is false in real applications; if so, load data from the original source (like a database) and cache it again.
// Example: Delete cached data
/*
echo "Attempting to delete cached data...<br>";
if ($memcached->delete($key)) {
echo "Data successfully deleted from cache for key '{$key}'.<br>";
} else {
echo "Failed to delete cached data!<br>";
echo "Result Code: " . $memcached->getResultCode() . "<br>";
}
// Try to get the deleted data again
echo "Trying to retrieve deleted data again...<br>";
$cachedDataAfterDelete = $memcached->get($key);
if ($cachedDataAfterDelete !== false) {
echo "Retrieved data (delete failed):<br>";
print_r($cachedDataAfterDelete);
} else {
echo "Data no longer in cache (expected behavior).<br>";
echo "Result Code: " . $memcached->getResultCode() . "<br>";
}
*/
// Example: Flush all cache (use with caution!)
/*
echo "Attempting to flush all cache...<br>";
if ($memcached->flush()) {
echo "All cache data has been cleared.<br>";
} else {
echo "Failed to flush cache!<br>";
echo "Result Code: " . $memcached->getResultCode() . "<br>";
}
*/
?>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
Access the memcached_test.php
file through your ServBay-configured local website to view the connection status, data set, and retrieval results.
Notes
- Make sure the Memcached package is running in ServBay.
- Memcached listens by default on
127.0.0.1
(orlocalhost
) at port11211
. Usually, you don't need to modify this. - If PHP fails to connect, check the Memcached package status and ensure your firewall doesn't block local connections.
- The
addServer
method of theMemcached
class only adds the server to the pool—it doesn't establish a persistent connection or check server availability immediately. Connections and operations actually occur when you call methods likeget
orset
. Check their return values or usegetResultCode()
to determine success.
Summary
ServBay provides developers with an exceptionally convenient way to use Memcached. Thanks to ServBay’s integrated Memcached server and the pre-installed, enabled memcached
PHP extension, you can rapidly utilize Memcached for efficient data caching in your local development environment—no complicated installation or configuration required. This lays a solid foundation for building high-performance PHP applications.