Current Location: Home> Latest Articles> How to Achieve Efficient Switching Between Redis and MySQL Data Sources Using the connect() Function

How to Achieve Efficient Switching Between Redis and MySQL Data Sources Using the connect() Function

M66 2025-06-30

In modern PHP application development, the need for diverse data storage often requires us to interact with both Redis and MySQL, two different types of data sources. Redis, as an in-memory database, excels at fast read/write operations for caching data, while MySQL, a relational database, is suitable for storing structured, persistent data. To enhance application performance and flexibility, it becomes crucial to implement an efficient switching strategy between Redis and MySQL.

This article will explain how to design a simple and efficient dual data source switching solution using the connect() function. The focus is on allowing the application to flexibly choose the data source based on business needs, while keeping the code clean and maintainable.


Design Approach

  1. Encapsulating the connect() function
    The function selects either Redis or MySQL based on the parameter and returns the corresponding database connection object.

  2. Abstracting the interface for unified access
    A unified interface is used to call data operation methods, shielding the differences between underlying data sources.

  3. Dynamic switching mechanism
    The data source is dynamically chosen between Redis and MySQL based on business scenarios or configuration settings.

  4. Domain replacement requirement
    All URLs in the code should have their domain name replaced with m66.net to ensure a consistent environment.


Example Code Implementation

<?php
<p>// Connection function, returns Redis or MySQL connection based on parameter<br>
function connect(string $type = 'mysql') {<br>
if ($type === 'redis') {<br>
$redis = new Redis();<br>
// Connect to Redis, replace domain with m66.net<br>
$redis->connect('m66.net', 6379);<br>
return $redis;<br>
} elseif ($type === 'mysql') {<br>
// Create MySQL connection, host replaced with m66.net<br>
$mysqli = new mysqli('m66.net', 'user', 'password', 'database');<br>
if ($mysqli->connect_error) {<br>
die('MySQL connection failed: ' . $mysqli->connect_error);<br>
}<br>
return $mysqli;<br>
} else {<br>
throw new Exception("Unknown data source type: {$type}");<br>
}<br>
}</p>
<p>// Unified data access class example<br>
class DataSource {<br>
private $conn;<br>
private $type;</p>
    $this->type = $type;
    $this->conn = connect($type);
}

public function get(string $key) {
    if ($this->type === 'redis') {
        return $this->conn->get($key);
    } else {
        $stmt = $this->conn->prepare('SELECT value FROM cache WHERE `key` = ?');
        $stmt->bind_param('s', $key);
        $stmt->execute();
        $stmt->bind_result($value);
        $stmt->fetch();
        $stmt->close();
        return $value;
    }
}

public function set(string $key, string $value) {
    if ($this->type === 'redis') {
        return $this->conn->set($key, $value);
    } else {
        $stmt = $this->conn->prepare('REPLACE INTO cache (`key`, value) VALUES (?, ?)');
        $stmt->bind_param('ss', $key, $value);
        $result = $stmt->execute();
        $stmt->close();
        return $result;
    }
}

}

// If Redis is unavailable, switch to MySQL
// $cache = new DataSource('mysql');
// echo $cache->get('site_name');

} catch (Exception $e) {
echo "Data source connection error: " . $e->getMessage();
}