Encapsulation of CACHE operations and best practices

Source: Internet
Author: User
As a WEB developer, CACHE is no longer familiar to us. But have you really studied how to make it more "elegant? Next we will take the more common Memcache as an example to talk about several common encapsulation methods for CACHE operations, and recommend a best practice I think. If you have a better solution, please kindly advise :) why is it encapsulated ?? Php

As a WEB developer, CACHE is no longer familiar to us. But have you really studied how to make it more "elegant? Next we will take the more common Memcache as an example to talk about several common encapsulation methods for CACHE operations, and recommend a best practice I think. If you have a better solution, please kindly advise :) why encapsulate it? ? Php

As a WEB developer, CACHE is no longer familiar to us. But have you really studied how to make it more "elegant? Next we will take the more common Memcache as an example to talk about several common encapsulation methods for CACHE operations, and recommend a best practice I think. If you have a better solution, please kindly advise :)

Why encapsulation?
 addServers('127.0.0.1', 11211);$key = 'test';$duration = 3600;$value = $mc->get($key);if ($mc->getResultCode() == Memcached::RES_NOTFOUND) {    $value = getValueFromDB();    $mc->set($key, $value, $duration);}

Those who use the CACHE for the first time often write the above Code. Simple and effective. It is no longer appropriate to write a Hello World file, but it is too low to write it when the CACHE is actually used in the project. There is no exception handling and Retry Mechanism, Server Load balancer cannot be performed, and a large number of duplicate codes ...... When you are unable to cope with the tedious maintenance, you will find a solution to these problems, namely encapsulation.

The advantages of encapsulation are obvious:
1. Reduce the amount of code to improve readability and reusability;
2. Various functions such as server Load balancer, data compression, key-value HASH, exception handling, and retry mechanisms can be added to the encapsulation layer to improve maintainability and robustness.

So the question is, how can we encapsulate it?

Instance handle Encapsulation
 _ MC = new Memcached ();? ? ? ? $ This-> _ MC-> addServers (self: MC_IP, self: MC_PORT );? ? }? ? Public function get ($ key ){? ? ? ? Return $ this-> _ MC-> get ($ key );? ? }? ? Public function set ($ key, $ value, $ duration ){? ? ? ? Return $ this-> _ MC-> set ($ key, $ value, $ duration );? ? }? ? Public function missed (){? ? ? ? Return $ this-> _ MC-> getResultCode () = Memcached: RES_NOTFOUND ;? ? } // Call the code $ key = 'test'; $ duration = 3600; $ mcHandle = new MemCacheHandle (); $ value = $ mcHandle-> get ($ key );? If ($ mcHandle-> missed () {$ value = getValueFromDB (); $ mcHandle-> set ($ key, $ value, $ duration );}

As you may say, this does not seem to be much different from non-encapsulation, but it is just missing a sentence about addServers. But let's see what can we do with such a layer of encapsulation:

1. Isolate server configuration information from Business Code and perform load balancing in the constructor;
2. You can perform unique HASH on the KEY value in the get method to unify the KEY value length to avoid excessive keys;
3. the stored data can be compressed in the set method to reduce the resource occupation of the server;
4. Exception Handling, LOG recording, or Retry Mechanism can be performed in get and set methods;
5. Hide the details of Memcache. you can replace it with redis, which is completely transparent to users.

Although the results are gratifying, there is still a problem: A MemCacheHandle must be instantiated in every place where the CACHE is used. Multiple instances must be instantiated multiple times. Although you can hold instances in the Business Code, how many times can you use instances across business lines and code libraries?

Static Method Encapsulation
 Get ($ key);} public static function set ($ key, $ value, $ duration) {return self: _ getInstance ()-> set ($ key, $ value, $ duration);} public static function missed () {return self: _ getInstance ()-> missed ();} private static function _ getInstance () {if (! Isset (self ::$ _ INSTANCE) {self ::$ _ INSTANCE = new MemCacheHandle () ;}return self ::$ _ INSTANCE ;}} // call the code $ key = 'test'; $ duration = 3600 ;? $ Value = MCache: get ($ key); if (MCache: missed () {$ value = getValueFromDB (); MCache: set ($ key, $ value, $ duration );}?

You may ask: This is not object-oriented. What are the advantages of static method encapsulation?

1. Hiding the instantiation process, missing a code, and less using a variable is visible and affordable;
2. It is important to use the singleton mode internally (which can be changed to the connection pool later) to avoid repeated instantiation and leave the business side with no worries about calling;

It seems that the code at the calling end has been simplified to the header. Reading, judging, and writing are indispensable. But is that true?

Best Practice: static method + closure Encapsulation
 

If you have never used PHP closures (provided in version 5.3), I think you can't say anything here.

The caller only knows that a layer of Cache is required before the value of the slave database, and it is enough to specify the key value and lifecycle used. So why do we need to care about the specific logic? No key, duration, or other variables can be used. Even the most basic three statements, read, judge, and write, are encapsulated.

If there is no temporary variable, you can use a single code. This is the perfect encapsulation.

Original article address: For the encapsulation and best practices of CACHE operations, I would like to thank the original author for sharing them.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.