Home Backend Development PHP Tutorial How to use multiple database connections in CakePHP?

How to use multiple database connections in CakePHP?

Jun 04, 2023 am 08:21 AM
cakephp multiple databases Data Connections

CakePHP is a popular PHP development framework that provides the basic functionality and structure needed to quickly develop web applications. In modern applications, it has become a common requirement to use multiple database connections, for example, to establish a master-slave database connection or to shard data into different databases. This article will introduce how to use multiple database connections in CakePHP.

Default database connection in CakePHP

Before we begin, let us first understand the default database connection in CakePHP. CakePHP uses configuration files to manage database connection information, which is usually stored in the config/app.php file. This file contains a configuration array, in which database connection configuration information can be set in the default subkey of the array.

By default, CakePHP uses MySQL as the primary database connection. The following is a sample code:

    'Datasources' => [
        'default' => [
            'className' => 'CakeDatabaseConnection',
            'driver' => 'CakeDatabaseDriverMysql',
            'persistent' => false,
            'host' => 'localhost',
            'username' => 'myuser',
            'password' => 'mypass',
            'database' => 'mydb',
            'encoding' => 'utf8mb4',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
            'quoteIdentifiers' => false,
            'log' => false,
        ],
    ],
Copy after login

In the above configuration information, we can see several general items, such as the class name of the database connection, driver type, user name and password, etc.

Using multiple database connections

To use multiple database connections, we can create a new database connection by copying the default subkey above. For example, the following code creates a new connection named secondary:

    'Datasources' => [
        'default' => [
            'className' => 'CakeDatabaseConnection',
            'driver' => 'CakeDatabaseDriverMysql',
            '...
        ],
        'secondary' => [
            'className' => 'CakeDatabaseConnection',
            'driver' => 'CakeDatabaseDriverPostgres',
            'persistent' => false,
            'host' => 'localhost',
            'username' => 'myuser',
            'password' => 'mypass',
            'database' => 'mydb2',
            'encoding' => 'utf8',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
            'quoteIdentifiers' => false,
            'log' => false,
        ],
    ],
Copy after login

In the above code, we can see the new connection configuration items, including different class names, driver types, user names and passwords, etc. . Please note that for example, for sensitive information such as username and password, we should use the encrypt() and decrypt() functions in the Crypt class to encrypt and decrypt.

Using different connections

Now that we have set up multiple database connections, the next step is to use them in the application. In CakePHP, we can use the ConnectionManager class to access different connections. The following is the sample code:

// 使用默认连接
$users = TableRegistry::get('Users');

// 使用secondary连接
$secondaryConn = ConnectionManager::get('secondary');
$secondaryUsers = TableRegistry::get('Users', [
    'connection' => $secondaryConn
]);
Copy after login

In the above code, we can see how we use the ConnectionManager class to obtain different connections. Once we have the connection, we can use the TableRegistry class to get the data table object associated with the connection. For the default connection, we can omit not passing the connection option.

Extending the use of connections

When making use of connections, we can further extend it to meet the needs of the application. For example, we can create a custom connection class by inheriting CakePHP's database connection class so that we can better handle connections. The following is a sample code:

class CustomMySqlConnection extends MySqlConnection
{
    public function __construct($config)
    {
        parent::__construct($config);
        $this->_isCustom = true;
    }

    public function customFunction()
    {
        return "Hello from CustomMySqlConnection!";
    }
}

// 使用CustomMySqlConnection来创建连接
'custom' => [
    'className' => 'CustomMySqlConnection',
    'driver' => 'CakeDatabaseDriverMysql',
    '...
],

// 获取custom连接并调用自定义函数
$customConn = ConnectionManager::get('custom');
$customConn->customFunction();
Copy after login

In the above code, we created a class named CustomMySqlConnection to extend the default MySqlConnection class in CakePHP. This class adds a custom function and sets the _isCustom variable to true so that we can distinguish it from the original connection in the application.

Conclusion

By using the above methods, we can easily set up and use multiple database connections in CakePHP to support complex application requirements. Although these connections look very similar, using the ConnectionManager and TableRegistry classes to obtain and manipulate them gives us the flexibility to use and manage them in our applications.

The above is the detailed content of How to use multiple database connections in CakePHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1250
24
CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

How to create custom pagination in CakePHP? How to create custom pagination in CakePHP? Jun 04, 2023 am 08:32 AM

CakePHP is a powerful PHP framework that provides developers with many useful tools and features. One of them is pagination, which helps us divide large amounts of data into several pages, making browsing and manipulation easier. By default, CakePHP provides some basic pagination methods, but sometimes you may need to create some custom pagination methods. This article will show you how to create custom pagination in CakePHP. Step 1: Create a custom pagination class First, we need to create a custom pagination class. this

How to use the database query builder in CakePHP? How to use the database query builder in CakePHP? Jun 04, 2023 am 09:02 AM

CakePHP is an open source PHPMVC framework which is widely used in web application development. CakePHP has many features and tools, including a powerful database query builder for interactive performance databases. This query builder allows you to execute SQL queries using object-oriented syntax without having to write cumbersome SQL statements. This article will introduce how to use the database query builder in CakePHP. Establishing a database connection Before using the database query builder, you first need to create a database connection in Ca

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

How does CakePHP handle file uploads? How does CakePHP handle file uploads? Jun 04, 2023 pm 07:21 PM

CakePHP is an open source web application framework built on the PHP language that simplifies the development process of web applications. In CakePHP, processing file uploads is a common requirement. Whether it is uploading avatars, pictures or documents, the corresponding functions need to be implemented in the program. This article will introduce how to handle file uploads in CakePHP and some precautions. Processing uploaded files in Controller In CakePHP, uploaded files are usually processed in Cont

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

See all articles