How to use memcache in php

The Memcache class

Represents a connection to a set of memcache servers.

Class synopsis

addServer (
string $host ,
int $port = 11211 ,
bool $persistent = ? ,
int $weight = ? ,
int $timeout = ? ,
int $retry_interval = ? ,
bool $status = ? ,
callable $failure_callback = ? ,
int $timeoutms = ?
): bool

setServerParams (
string $host ,
int $port = 11211 ,
int $timeout = ? ,
int $retry_interval = false ,
bool $status = ? ,
callable $failure_callback = ?
): bool

Table of Contents

  • Memcache::add — Add an item to the server
  • Memcache::addServer — Add a memcached server to connection pool
  • Memcache::close — Close memcached server connection
  • Memcache::connect — Open memcached server connection
  • Memcache::decrement — Decrement item’s value
  • Memcache::delete — Delete item from the server
  • Memcache::flush — Flush all existing items at the server
  • Memcache::get — Retrieve item from the server
  • Memcache::getExtendedStats — Get statistics from all servers in pool
  • Memcache::getServerStatus — Returns server status
  • Memcache::getStats — Get statistics of the server
  • Memcache::getVersion — Return version of the server
  • Memcache::increment — Increment item’s value
  • Memcache::pconnect — Open memcached server persistent connection
  • Memcache::replace — Replace value of the existing item
  • Memcache::set — Store data at the server
  • Memcache::setCompressThreshold — Enable automatic compression of large values
  • Memcache::setServerParams — Changes server parameters and status at runtime

User Contributed Notes 1 note

It helps to know that for this extension to work, you need a server with ‘Memcached’ (a service independent of PHP) installed and running as a service.

The documentation herein refers a lot to ‘memcache_host’. This is not an arbitrary string, but should be a host name (eg localhost) or an IP address of a server running memcached.

If you have just installed the php memcache extension then you will not necessarily have memcached installed as well

Источник

Memcached

For those confuse about the memcached extension and the memcache extension, the short story is that both of them are clients of memcached server, and the memcached extension offer more features than the memcache extension.

GOTCHA: Recently I was tasked with moving from PECL memcache to PECL memcached and ran into a major problem — memcache and memcached serialize data differently, meaning that data written with one library can’t necessarily be read with the other library.

For example, If you write an object or an array with memcache, it’s interpreted as an integer by memcached. If you write it with memcached, it’s interpreted as a string by memcache.

tl;dr — You can’t safely switch between memcache and memcached without a either a cache flush or isolated cache environments.

$memcache = new Memcache ;
$memcacheD = new Memcached ;
$memcache -> addServer ( $host );
$memcacheD -> addServers ( $servers );

$checks = array(
123 ,
4542.32 ,
‘a string’ ,
true ,
array( 123 , ‘string’ ),
(object)array( ‘key1’ => ‘value1’ ),
);
foreach ( $checks as $i => $value ) print «Checking WRITE with Memcache\n» ;
$key = ‘cachetest’ . $i ;
$memcache -> set ( $key , $value );
usleep ( 100 );
$val = $memcache -> get ( $key );
$valD = $memcacheD -> get ( $key );
if ( $val !== $valD ) print «Not compatible!» ;
var_dump ( compact ( ‘val’ , ‘valD’ ));
>

Читайте также:  Решить кубическое уравнение питон

print «Checking WRITE with MemcacheD\n» ;
$key = ‘cachetest’ . $i ;
$memcacheD -> set ( $key , $value );
usleep ( 100 );
$val = $memcache -> get ( $key );
$valD = $memcacheD -> get ( $key );
if ( $val !== $valD ) print «Not compatible!» ;
var_dump ( compact ( ‘val’ , ‘valD’ ));
>
>

## Installing Memcached on Ubuntu

To install Memcached on Ubuntu, go to terminal and type the following commands −

$sudo apt-get update
$sudo apt-get install memcached

## Confirming Memcached Installation

To confirm if Memcached is installed or not, you need to run the command given below. This command shows that Memcached is running on the default port 11211.

To run Memcached server on a different port, execute the command given below. This command starts the server on the TCP port 11111 and listens on the UDP port 11111 as a daemon process.

$memcached -p 11111 -U 11111 -u user -d

You can run multiple instances of Memcached server through a single installation.

The module also supports SASL authentication, it just isn’t documented sadly. You’ll need to run the following code:

$m = new Memcached ();
$m -> setOption ( Memcached :: OPT_BINARY_PROTOCOL , true );
$m -> setSaslAuthData ( «user-1» , «pass» );
?>

You need to enable the «memcached.use_sasl = 1» ini option for memcached in the php.ini file.

Источник

Using Memcached with PHP

php memcached

Memcached is an object caching framework. It is essentially used to cache the database queries, making a difference in dynamic websites like Drupal and WordPress to serve pages quicker. It can moreover significantly decrease resource use on an active web server by reducing calls to the database.

Memcached is a distributed memory caching system. It speeds up websites having large dynamic databases by storing database objects in Dynamic Memory to reduce the pressure on a server whenever an external data source requests a read. A Memcached layer reduces the number of times database requests are made.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

In Layman’s Terms

Let’s conjure up an analogy. Suppose you are a manager of a DVD store that has lots of movies and games with different genres like sci-fi, history, and drama. You assign some keys to the movies that customers ask for a lot and paste them on a front counter for the ease of the storekeeper. Now, these assigned keys can be circulated among your customers and whenever these customers request that particular key, your storekeeper doesn’t have to get into the details of the movies but just fetch them the DVDs. This will increase the response time of your storekeeper. All the requests for which the keys are not found will be looked into in detail to find out which movies the customers are requesting.

Читайте также:  Input vertical align css

The delivery process will be as rapid as the assignment of the keys. These keys act as speed buffer by moving all the details one has to look into for fetching movies.

These same things happen to the content your web page is serving. Memcached stores the values (v) with the key (k) and retrieves the values (v) with the key (k) without even parsing the database queries and stays away from all these hassles.

Why Memcached?

It decreases the response time of your web pages, which in return enhances the overall customer’s experience. A better response time allows users to fetch data seamlessly.

Get Ready for Core Web Vitals Update

Ebook to Speed Up Your Website Before You Start Losing Traffic.

Источник

How to Use Memcached in PHP for Faster Load Times

Hamburger menu

PHP and Memcached work together seamlessly for data caching. This article will step you through how to access and manage data within Memcached using PHP.

If you haven’t done so yet, follow these instructions to install Memcached in a Windows or Linux environment. Then come back to this article to for optimizing your application speeds for faster load times.

The Data Set

When working with PHP and database results, I generally convert the results into an array that can be looped through using a simple for loop. For me, it’s easier to maintain and read, and looping over array data is much simpler than looping over query data.

For the purposes of this article, we’ll create a set of dummy data inside an array that we can easily loop through:

$my_array = [ 
[
"id" => 1,
"title" => "Orange"
],
[
"id" => 2,
"title" => "Banana"
],
[
"id" => 3,
"title" => "Apple"
]
];

Learn more about PHP arrays here if you’re looking to learn about them or need to brush up on your skills.

Initialize Memached

Now, let’s initialize Memcached. There are two lines of code required to do this:

$memcached = new Memcache;
$memcached->addServer("127.0.0.1", 11211);

The first command initializes a new Memcached instance, assuming that Memcached is running on the server. If it’s not running and you try to run your PHP script, your whole page should error.

The second command creates a new Memcached instance to store data if it has not already been created. In the first argument, we’re assigning 127.0.0.1 as the local IP address for the server location, and port 11211 as the port to access Memcached memory in the second argument.

If your page executes without an error message, then Memcached has been initialized successfully and we can move onto data management and caching.

Setting Memcached Data

First, let’s set some data to a new Memcached key called «data». We’ll use the $my_array variable’s data above to store in this key:

$memcached->set("data", serialize($my_array), false, 300);

In this example, we’re setting the $my_array data to a key named «data» that will be stored in Memcached memory.

Читайте также:  Read text file python encoding

The data will exist in memory for 300 seconds or 5 minutes. Once this timeframe has expired, the data will no longer be available in this key until it is stored again.

A few important things to note:

  • Make sure you’re using unique key names when setting your data. If you use the same key name for different sets of data, the previous data attached to this key will only be available. Using the Memcached set() command overwrites any existing data within the specified key if it exists, or it creates a new data set.
  • Data stored in Memcached memory must be serialized to string format. Like browser cookies, complex objects cannot be stored. When accessing the data later, you must unserialize that data so you can access it as needed.

Reading Memcached Data

All Memcached data is stored within a unique key name. These key names are identified with a string value, like an ID to access the data.

Each key name is unique to one another and provides a different set of data that you store within each key.

Say we have a key with the name «data». If we wanted to access that key’s data from Memcached, we could do so with these lines of code:

$my_data = $memcached->get("data");
$my_data = unserialize($my_data);

That’s it! You now have a local copy of the Memcached key «data» stored in a local variable $my_data for use.

If you now loop through the data, assuming that our $my_array variable data was stored in Memcached at this key name, we could loop over it easily:

for ($i = 0; $i < sizeof($my_data); $i++) echo $my_data[$i]["id"] . ' - ' . $my_data[$i]["title"];
>

// 1 - Orange
// 2 - Banana
// 3 - Apple

I like to add a failsafe for Memcached data retrievals in case the data has not been stored at that specific key yet:

$my_data = $memcached->get("data");

if ($my_data) $my_data = unserialize($data);
> else $my_data = [];
>

This checks to make sure the retrieved data exists before accessing it locally, which prevents errors in your application.

Deleting Memcached Data

Deleting Memcached data is simple. All you need to do is call the Memcached delete() method and provide the key name:

The data in the «data» key is now no longer available and cannot be accessed unless stored again under the same key name.

Flush All Memcached Data

If you want to just flush all of the data stored in Memcached, you can do so without providing a specific key name:

Conclusion

Now that you have an understanding of how Memcached works with PHP, you can easily optimize your applications for speed and faster load times by storing your data resultsets into memory for a set period of time.

Comments

There are no comments yet. Start the conversation!

Источник

Оцените статью