What does memcached do in php?

In this tutorial we will learn about implementation of memcached in php and mysql. I will just show you a simple example of using memcached with PHP and mysql. Memcached is a general-purpose in-memory, high-performance and distributed memory object caching system.

Memcached is very useful and important in web technology to make faster website. Using memcached, you can implement memcached in block wise code or your whole program. Memcached is implementing on your sql query to reduce the server RAM load.

Recommendation:

I recommend using memcached very carefully because bad implementation of memcached results slows your query or stuck the whole program.

Tips:   

1. After fully finalize your query, you should implement memcached in your mysql query.

2. While defining the memcached  key be careful to use unique key for every chunk of your code.

Code Implementation:

Before using memcached in your code, You need to install and configure the memcached. For installation and configuration read this tutorial

How to install memcache with wamp and PHP 5.3

Now after installation, we need to make server connection for memcached. For memcached server connection.

/* ======== Memcached Server Connection ========= */
$memcache = new Memcached();
$memcache->addServer('localhost', 11211) or die ("Could not connect");
/* ======== Memcached Server Connection ========= */

Now same time make database connection

/*========== Database Connection Code Start Here ============ */

define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", ""); // set database user
define ("DB_PASS",""); // set database password
define ("DB_NAME",""); // set database name

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");

/*========= Database Connection Code End Here ============== */

Full code:

While setting memcached key value, it is necessary to use unique key.



The Memcache module can provide a handy procedural and object-oriented interface to Memcached, a highly effective caching daemon that was specially designed to decrease database load in dynamic web applications.

The Memcache module can also provide a session handler (Memcache).

For more information about Memcached can be found at » http://www.danga.com/memcached/.

Installation

This PECL extension has not been included with PHP. Additional information such as new versions, downloads, source files, developer information, and CHANGELOG can be found here: »https://pecl.php.net/package/memcache.

To use these functions, we must compile PHP with memcache support by using the --enable-memcache [= DIR] option. We may optionally disable memcache session handler support by specifying --disable-memcache-session.

Windows users can enable php_memcache.dll inside php.ini to use these functions. We need to download the DLL of this PECL extension from the »PHP Downloads or » http://snaps.php.net/page.

Requirements

Memcache module can use the functions of » zlib to support on-the-fly data compression. The Zlib has required to install this module.

Resource Types

There is only one resource type used in the emcache module - it's the link identifier for cache server connection.

PHP 4.3.3 or newer has required to use the Memcache extension.

Runtime Configuration

The behavior of these functions can depend on settings in php.ini.

Memcache Configuration Options

NameDefaultChangeableChangelog
memcache.allow_failover "1" PHP_INI_ALL Available since memcache 2.0.2.
memcache.max_failover_attempts "20" PHP_INI_ALL Available since memcache 2.1.0.
memcache.chunk_size "8192" PHP_INI_ALL Available since memcache 2.0.2.
memcache.default_port "11211" PHP_INI_ALL Available since memcache 2.0.2.
memcache.hash_strategy "standard" PHP_INI_ALL Available since memcache 2.2.0.
memcache.hash_function "crc32" PHP_INI_ALL Available since memcache 2.2.0.
session.save_handler "files" PHP_INI_ALL Supported since memcache 2.1.2
session.save_path "" PHP_INI_ALL Supported since memcache 2.1.2
memcache.protocol ascii >PHP_INI_ALL Supported since memcache 3.0.0
memcache.redundancy 1 >PHP_INI_ALL Supported since memcache 3.0.0
memcache.session_redundancy 2 >PHP_INI_ALL Supported since memcache 3.0.0
memcache.compress_threshold 20000 >PHP_INI_ALL Supported since memcache 3.0.3
memcache.lock_timeout 15 >PHP_INI_ALL Supported since memcache 3.0.4

For a detailed description of the PHP_INI_* constants, refer to the documentation Where a configuration setting may be set.

  • memcache.allow_failover boolean − Whether to transparently failover to other servers on errors.

  • memcache.max_failover_attempts integer − Defines how many servers to try when setting and getting data. Used only in conjunction with memcache.allow_failover.

  • memcache.chunk_size integer − Data will be transferred in chunks of this size, setting the value lower requires more network writes. Try increasing this value to 32768 if noticing otherwise inexplicable slowdowns.

  • memcache.default_port string − The default TCP port number to use when connecting to the memcached server if no other port is specified.

  • memcache.hash_strategy string − Controls which strategy to use when mapping keys to servers. Set this value to consistent to enable consistent hashing which allows servers to be added or removed from the pool without causing keys to be remapped. Setting this value to standard results in the old strategy being used.

  • memcache.hash_function string − Controls which hash function to apply when mapping keys to servers, crc32 uses the standard CRC32 hash while fnv uses FNV-1a.

  • session.save_handler string − Use memcache as a session handler by setting this value to memcache.

  • session.save_path string − Defines a comma separated of server urls to use for session storage, for example "tcp://host1:11211, tcp://host2:11211". Each url may contain parameters which are applied to that server, they are the same as for the Memcache::addServer() method. For example "tcp://host1:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

  • memcache.protocol string

  • memcache.redundancy integer

  • memcache.session_redundancy integer

  • memcache.compress_threshold integer

  • memcache.lock_timeout integer

Basic usage

In this example, an object is being saved in a cache and then retrieved back. Object and other non-scalar types are serialized before saving, so it's impossible to store resources (i.e. connection identifiers and others) in a cache.

Example 1

connect("localhost", 11211) or die ("Could not connect");
   $version = $memcache->getVersion();
   
   echo "Server's version: ".$version."
\n"; $tmp_object = new stdClass; $tmp_object->str_attr = "test"; $tmp_object->int_attr = 123; $memcache->set("key", $tmp_object, false, 10) or die ("Failed to save data at the server"); echo "Store data in the cache (data will expire in 10 seconds)
\n"; $get_result = $memcache->get("key"); echo "Data from the cache:
\n"; var_dump($get_result); ?>

Using memcache session handler

Example 2

Predefined Constants

Memcache Constants

Sr.NoName & Description
1

MEMCACHE_COMPRESSED (integer)

Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() and Memcache::replace().

2

PMEMCACHE_HAVE_SESSION (integer)

1 if this Memcache session handler is available, 0 otherwise.

3

MEMCACHE_USER1 (integer)

Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().

4

MEMCACHE_USER2 (integer)

Used to trn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().

5

MEMCACHE_USER3 (integer)

Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().

6

MEMCACHE_USER4 (integer)

Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().

Memcache Functions

Following are the Memcache functions −

Sr.NoFunction & Description
1

Memcache::add()

This function can add an item to server.

2

Memcache::addServer()

This function can add a memcached server to connection pool.

3

Memcache::close()

This function can close the memcached server connection.

4

Memcache::connect()

This function can open a memcached server connection.

5

memcache_debug()

This function can turn debug output on/off.

6

Memcache::decrement()

This function can decrement the item's value.

7

Memcache::delete()

This function can delete an item from the server.

8

Memcache::flush()

This function can flush all existing items at the server.

9

Memcache::get()

This function can retrieve an item from the server.

10

Memcache::getExtendedStats()

This function can get the statistics from all servers in a pool.

11

Memcache::getServerStatus()

This function can return the server status.

12

Memcache::getStats()

This function can get the statistics of the server.

13

Memcache::getVersion()

This function can return the version of the server.

14

Memcache::increment()

This function can increment the item's value.

15

Memcache::pconnect()

This function can open a memcached server persistent connection.

16

Memcache::replace()

This function can replace the value of an existing item.

17

Memcache::set()

This function can store the data at the server.

18

Memcache::setCompressThreshold()

This function can enable an automatic compression of large values.

19

Memcache::setServerParams()

This function can change the server parameters and status at runtime.

What is the use of memcached?

Memcached can serve cached items in less than a millisecond, and enables you to easily and cost effectively scale for higher loads. Memcached is popular for database query results caching, session caching, web page caching, API caching, and caching of objects such as images, files, and metadata.

What is the difference between Memcache and memcached?

They both have very basic difference while storing value. Memcache mostly considers every value as string whereas Memcached stores it value's original type. Thumbs up for your answer !

What is memcached in MySQL?

When using memcached to cache MySQL data, your application must retrieve data from the database and load the appropriate key-value pairs into the cache. Then, subsequent lookups can be done directly from the cache.

Can memcached be used as a database?

keep in mind that memcache is a simple key/value storage, not a database capable of any search or join logic.