Implementing a Redis Multi-Database Singleton Wrapper in ThinkPHP

This guide demonstrates how to set up a Redis multi-database singleton wrapper in a ThinkPHP project, covering prerequisite installation, configuration of connection parameters, creation of a custom Redis class with static instance management, and example usage of Redis commands across different databases.

php Courses
php Courses
php Courses
Implementing a Redis Multi-Database Singleton Wrapper in ThinkPHP

1. Preparation: install the phpredis extension or the Predis client via Composer. composer require predis/predis 2. Configure Redis connection information in app\config\cache.php:

'redis' => [
    // driver
    'type' => 'redis',
    // host
    'host' => Env::get('redis.host'),
    // port
    'port' => Env::get('redis.port'),
];

Additional options can be set as shown:

protected $options = [
    'host'       => '127.0.0.1',
    'port'       => 6379,
    'password'   => '',
    'select'     => 0,
    'timeout'    => 0,
    'expire'     => 0,
    'persistent' => false,
    'prefix'     => '',
    'tag_prefix' => 'tag:',
    'serialize'  => [],
];

3. Create Redis.php under app\common that extends ThinkPHP's Redis driver and provides a static singleton method for each database.

<?php
namespace app\common;
use think\facade\Config;
use think\cache\driver\redis as ThinkRedis;

class Redis extends ThinkRedis {
    protected $hash;
    protected static $instance = [];

    private function __construct($db) {
        $options = Config::get('cache.stores.redis');
        $options['select'] = $db;
        $this->hash = $db;
        $this->options = array_merge($this->options, $options);
        parent::__construct();
    }

    private function __clone() {}

    public static function instance($db = 0) {
        if (!isset(self::$instance[$db])) {
            self::$instance[$db] = new self($db);
        }
        return self::$instance[$db];
    }

    public function __destruct() {
        self::$instance[$this->hash]->close();
        unset(self::$instance[$this->hash]);
    }
}

4. Use the wrapper to interact with Redis databases:

use app\common\Redis;

$redis = Redis::instance(4);
$redis->hSet('user:1', 'userName', 'admin');

Redis::instance(1)->hSet('user', 'name', 'admin1');
Redis::instance(2)->hSet('user', 'name', 'admin2');
Redis::instance(3)->hSet('user', 'name', 'admin3');

For more command references, consult the Redis command manual.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendCacheredisPHPSingletonThinkPHP
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.