"End" using Composer to perfect your PHP framework (iii)--redis cache

Source: Internet
Author: User
Tags php framework redis server

For this tutorial sample code see Https://github.com/johnlui/My-First-Framework-based-on-Composer

Review

In the last two articles, we completed the design of the view load class and the mail mail sending class, and completed two pluggable components. In this article we will build another pluggable component, the ' Redis interface ', and use it to build the ' MFFC ' cache service.

Introduction to Text Redis

' Redis ' is a high performance ' Key-value ' database whose ' value ' supports ' string ', ' Map (hash ') ', ' list ', ' Set ' and ' sorted sets ', Chinese translation into strings, dictionaries (hashes, in ' The best language in the world php ' is part of ' arrays ', lists, collections, and ordered collections.

We can use Redis as a cache to store the data that the system often needs to access. Redis has higher performance, better maintainability, and more powerful operational APIs than using files as a cache.

Redis Installation

The Redis website is http://redis.io/and can be easily downloaded and launched directly at the command line, which listens to the ' 6379 ' port by default.

After the Redis server is loaded and started, it is not possible to write a line of code to start using directly, and we also need to install ' client '. There are currently two ways to compare recommendations:

1. Install the Redis extension for PHP.

2. Use the Nrk/predis package.

Note: As a PHP extension installation, please print out ' phpinfo () ', find ' Loaded Configuration File ', edit this ' php.ini ' is only valid. Don't forget to ' reboot ' Apache or PHP-FPM.

Redis use

Here we select the ' Nrk/predis ' package as the Redis driver. Edit ' Composer.json ':

"Require": {  "Codingbean/macaw": "Dev-master",  "illuminate/database": "*",  "Filp/whoops": "*",  " Nette/mail ":" * ",  " Predis/predis ":" * "},

Run ' composer Update ' and wait for the installation to complete.

Then we're going to start building the Redis class and create a new ' services/redis.php ':

<?phpuse predis\client;/*** \redis*/class redis{Const Config_file = '/config/redis.php ';  protected static $redis;  public static function init () {self:: $redis = new Client (require Base_path.self::config_file);    public static function set ($key, $value, $time =null, $unit =null) {self::init ();          if ($time) {switch ($unit) {case ' H ': $time *= 3600;        Break          Case ' m ': $time *= 60;        Break        Case ' s ': Case ' Ms ': break;          Default:throw New InvalidArgumentException (' unit can only be H M s Ms ');      Break      } if ($unit = = ' ms ') {Self::_psetex ($key, $value, $time);      } else {Self::_setex ($key, $value, $time);    }} else {self:: $redis->set ($key, $value);    }} public static function get ($key) {self::init ();  Return self:: $redis->get ($key);    } public static function Delete ($key) {self::init ();  Return self:: $redis->del ($key); } Private Static function _setex ($key, $value, $time) {self:: $redis->setex ($key, $time, $value);  } private static function _psetex ($key, $value, $time) {self:: $redis->psetex ($key, $time, $value); }}

New configuration file ' config/redis.php ':

<?phpreturn [  ' host ' = ' 127.0.0.1 ',  ' port ' = 6379];

And then we can start testing and add in ' HomeController ':

Redis::set (' key ', ' value ', 5, ' s '); Echo redis::get (' key ');

Once run, comment out the line above and refresh it to see if ' value ' disappears from the page at the end of the set time.

Code Analysis

1. We created the ' \redis ' class, providing ':: Set () ', ':: Get () ' and '::d elete () ' Three static methods for adding, fetching, and deleting a pair of ' key-value '.

2. ':: Set () ' method supports setting the lifetime of ' key-value ' key-value pairs and supports ' h ', ' m ', ' s ' and ' Ms ' four units, representing hours, minutes, seconds, and milliseconds, so that they can be conveniently used for caching.

3. Strictly speaking, the cache class requires at least one basic operation to ' determine if key is still present ', so this class is just a slightly more powerful Redis interface.

4. Building a cache interface as an exercise, you can try to write it yourself. Select New Cache class or add an interface to the Redis class.

End

"End" using Composer to perfect your PHP framework (iii)--redis cache

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.