Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to achieve efficient caching when PHP uses redis as cache

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to achieve efficient caching when PHP uses redis as a cache". In the operation of actual cases, many people will encounter this dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Have you ever thought about how PHP can use redis as a cache:

Foreground and background modules share Model layer

However, every Model class cannot be cached, which is a waste of Redis resources

The foreground and background modules are free to decide whether to read data from the database or from the cache

No redundant code

Easy to use.

Here we first show the final effect of the implementation.

For the final code and instructions, please go to Github: https://github.com/yeszao/php-redis-cache.

Install and use the command now:

$composer install yeszao/cache

It can be used after simple configuration, please see the README description of Github.

1 final effect

Suppose that in the MVC framework, the model layer has a Book class and a getById method, as follows:

Class Book {public function getById ($id) {return $id;}}

After the addition of caching technology, the way the original method is called and the data structure returned should not be changed.

So, we hope that the final effect should be as follows:

(new Book)-> getById (100); / / the original, non-cached invocation method is the same, usually reading data from the database. (new Book)-> getByIdCache (100); / / use the cache key name: app_models_book:getbyid: + md5 (parameter list) (new Book)-> getByIdClear (100); / / delete the cache (new Book)-> getByIdFlush (); / / delete all caches corresponding to the getById () method, that is, delete app_models_book:getbyid:*. This method requires no parameters.

In this way, we can clearly understand what we are doing, and at the same time know the source function of the data, and be quoted in a completely uniform way, which can be said to kill three birds with one stone.

In fact, it is relatively simple to implement, that is, using PHP's magic method _ _ call () method.

2 _ _ call () method

Here is a brief explanation of the purpose of the _ _ call method.

In PHP, when we access a class method that does not exist, the _ _ call () method of that class is called.

(if the class method does not exist and the _ _ call () method is not written, PHP will report an error directly)

Suppose we have a Book class:

Class Book {public function _ call ($name, $arguments) {echo 'class Book does not exist method', $name, PHP_EOL;} public function getById ($id) {echo'my ID is', $id, PHP_EOL;}}

When calling the existing getById (50) method, the program prints: my ID is 50.

If you call the getAge () method that does not exist, the program executes into the _ _ call () method of class A, where it is printed that there is no method getAge for class Book.

This is how _ _ call works.

3 implementation details

Next we will take advantage of this feature of the _ _ call () method to implement the caching strategy.

From the example above, we can see that when the _ _ call () method is called, two parameters are passed in.

Name: the name of the method you want to call arguments: parameter list

We can make a fuss about the parameters.

Taking the Book class as an example, let's assume that its original structure is as follows:

Class Book {public function _ call ($name, $arguments) {/ / content to be filled} public function getById ($id) {return ['id' = > $id,' title' = > 'PHP caching technology'. $id];}}

Before we begin, we also confirm the connection to Redis, which must be used in the cache. Here we write a simple singleton class:

Class Common {private static $redis = null; public static function redis () {if (self::$redis = null) {self::$redis = new\ Redis ('127.0.0.1'); self::$redis- > connect ('redis');} return self::$redis;}

Then, we begin to populate the code of the _ _ call () method. For a specific description, please see the comments:

Class Book {public function _ call ($name, $arguments) {/ / because we mainly determine the specific operation based on the suffix of the method name, / / so if the passed $name length is less than 5, you can directly report an error if (strlen ($name)

< 5) {exit('Method does not exist.');}// 接着,我们截取 $name,获取原方法和要执行的动作,// 是cache、clear还是flush,这里我们取了个巧,动作// 的名称都是5个字符,这样截取就非常高效。$method = substr($name, 0, -5);$action = substr($name, -5);// 当前调用的类名称,包括命名空间的名称$class = get_class();// 生成缓存键名,$arguments稍后再加上$key = sprintf('%s:%s:', str_replace('\\', '_', $class), $method);// 都用小写好看点$key = strtolower($key);switch ($action) {case 'Cache':// 缓存键名加上$arguments$key = $key . md5(json_encode($arguments));// 从Redis中读取数据$data = Common::redis()->

Get ($key); / / if there is data if ($data! = = false) {$decodeData = json_decode ($data, JSON_UNESCAPED_UNICODE) in Redis; / / if it is not in JSON format, return it directly, otherwise return json parsed data return $decodeData = null? $data: $decodeData } / / if there is no data in the Redis, continue / / if the original method does not exist if (method_exists ($this, $method) = false) {exit ('Method does not exist.') } / / call the original method to get data $data = call_user_func_array ([$this, $method], $arguments); / / Save the data to Redis for next time use Common::redis ()-> set ($key, json_encode ($data), 3600) / / ends execution and returns the data return $data; break; case 'Clear': / / cache key name plus $arguments $key = $key. Md5 (json_encode ($arguments)); return Common::redis ()-> del ($key); break; case 'Flush': $key = $key. '*'; / / get all cache key names that conform to the $class:$method:* rule $keys = Common::redis ()-> keys ($key); return Common::redis ()-> del ($keys); break; default: exit ('Method does not exist.');}} / / other methods}

This achieves the effect we had at the beginning.

4 when in actual use

In practice, we need to make some changes to put this piece of code into a class

Then refer to this class in the base class of the model layer, and pass in the Redis handle, class object, method name, and parameters

This reduces code coupling and makes it more flexible to use.

This is the end of "how to achieve efficient caching when PHP uses redis as a cache". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report