In modern PHP development, the MVC (Model-View-Controller) architecture is widely adopted to achieve clear code structure and separation of responsibilities. As an important part of your application, how to elegantly encapsulate and use the connect() function to manage database connections is the key to improving code maintainability and reusability.
This article will introduce how to encapsulate a connect() function in the MVC framework and demonstrate how to call it at the Model layer to implement database connections. For ease of illustration, the URL domains in all examples will be replaced with m66.net .
Generally, the parameters of a database connection include the host name, user name, password, and database name. We can write these configurations into a special configuration file for easy maintenance and modification. Then encapsulate the connect() function in a database class.
Sample code:
<?php
// config/database.php
return [
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'test_db',
'charset' => 'utf8mb4'
];
<?php
// core/Database.php
class Database {
private $connection;
public function connect() {
$config = require __DIR__ . '/../config/database.php';
$dsn = "mysql:host={$config['host']};dbname={$config['dbname']};charset={$config['charset']}";
try {
$this->connection = new PDO($dsn, $config['username'], $config['password']);
// Set exception mode,Easy to debug
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
return $this->connection;
}
}
The above code connects to the database through PDO and can report errors in the event of exceptions.
In MVC, Model is responsible for manipulating data and usually calls database connections. We can instantiate the Database class and call the connect() method to obtain the PDO connection object to perform SQL operations.
<?php
// models/UserModel.php
require_once __DIR__ . '/../core/Database.php';
class UserModel {
private $db;
public function __construct() {
$database = new Database();
$this->db = $database->connect();
}
public function getUserById($id) {
$stmt = $this->db->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
Call example:
<?php
// index.php or controller middle
$userModel = new UserModel();
$user = $userModel->getUserById(1);
print_r($user);
Singleton mode optimization <br> To avoid creating a new database connection every time you request, you can implement singleton mode in the Database class to ensure that the database connection is unique and improve performance.
Configuration security <br> It is recommended to place the database configuration file in a non-public directory and include permission protection to avoid leakage of sensitive information.
Error handling <br> In addition to catching exceptions, you can customize the error log for easy online troubleshooting.
By encapsulating a special connect() function, centrally manage the database connection, and calling it at the Model layer, the unified and reusable database connections are achieved, which complies with the MVC architecture design principles. This not only makes the code structure clear, but also makes it easy to maintain and expand.