Memcached could be a very efficient way to scale your web applications. Memcached lets you store data into the cache of your memory and quickly retrieve data when you need. So, it is usually very fast for data storage. But the darker side is that it’s extremely volatile. Your machine crashes or restarts and all the data are gone. Still, memcached is widely used as a caching device to store temporary data for decreasing the load on mysql database.
Memcached is supported by many of the scripting languages. PHP has excellent support it. They have a PECL extension for interacting with Memcached.
=====================
Setting Things Up
=====================
1) Install Memcached on your machine.
2) Install Memcached PECL extension for PHP.
3) Activate Memcache.
1) Installing Memcached:
To install memcached on your Ubuntu type the following command on your terminal and press enter:
1 |
sudo apt-get install memcached |
To install on Windows:
1. Download memcache from code.jellycan.com/memcached/ [grab the ‘win32 binary’ version]
2. Install memcache as a service:
* Unzip and copy the binaries to your desired directory (eg. c:\memcached) [you should see one file, memcached.exe] – thanks to Stephen for the heads up on the new version
* If you’re running Vista, right click on memcached.exe and click Properties. Click the Compatibility tab. Near the bottom you’ll see Privilege Level, check “Run this program as an administrator”.
* Install the service using the command: c:\memcached\memcached.exe -d install from the command line
* Start the server from the Microsoft Management Console or by running one of the following commands: c:\memcached\memcached.exe -d start, or net start “memcached Server”
2) Installing The PECL Extension:
On Ubuntu, use the command on terminal:
1 |
sudo pecl install memcached |
On windows, you need to get the memcached PECL extension, put it into the PHP’s extension directory. You might get the file at: http://downloads.php.net/pierre/
Add the extension to php.ini.
On Linux:
1 |
extension=memcache.so |
On Windows:
1 |
extension=php_memcache.dll |
3) Activate:
Make sure that Memcached is running as a daemon/service. If not, use the command:
1 |
memcached -d |
Now start using memcached 🙂
Memcached Demo: How to store an array ?
The Memcached PECL extension has a built in class “Memcache” which we will use to work with Memcached.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $m = new Memcache; // Create a new Memcache Object $m->connect("localhost"); // Connect to your own machine // Define an array $array = array("name" => "maSnun", "email" => "masnun@leevio.com"); // Store it into memcache $m->set("data",$array); // Lets get the data back $a = $m->get("data"); // Print the data echo "Name: {$a['name']} \n"; echo "Email: {$a['email']} \n"; ?> |
Pretty easy… Isn’t it?