首批通过分布式安全可靠测评,为关键业务系统打造
CakePHP 连接 OceanBase 数据库示例程序
更新时间:2026-04-09 14:12:04
概述
CakePHP 是一个 PHP 快速开发框架,使用了关联数据映射、前端控制器和 MVC 等设计模式。 本文介绍如何在 CakePHP 中连接 OceanBase 数据库,实现基本的 CRUD(增删改查)操作。
功能适用性
CakePHP 适用于 OceanBase 数据库 MySQL 模式。
前提条件
在使用 CakePHP 之前,确认:
- 您已完成部署 OceanBase 数据库并且创建了 MySQL 模式用户租户。创建用户租户的详细信息,参见 创建租户 。
操作步骤
步骤一:获取数据库连接串
联系 OceanBase 数据库部署人员获取连接串,例如:
obclient -h$host -P$port -u$user_name -p$password -D$database_name
参数说明:
$host:连接 IP。ODP 连接用 ODP 地址;直连用 OBServer IP。$port:连接端口。ODP 默认2883;直连默认2881。$database_name:数据库名称。注意
连接租户的用户需要拥有该数据库的
CREATE、INSERT、DROP和SELECT权限。更多有关用户权限的信息,请参见 MySQL 模式下的权限分类。$user_name:连接账户。ODP 格式:用户@租户#集群或集群:租户:用户;直连格式:用户@租户。$password:账户密码。
更多连接串的信息,请参见通过 OBClient 连接 OceanBase 租户。
示例如下:
obclient -hxxx.xxx.xxx.xxx -P2881 -utest_user001@mysql001 -p****** -Dtest
步骤二:安装 CakePHP 环境
- 安装 PHP 8.3 及相关扩展:
apt update
apt install -y software-properties-common
add-apt-repository ppa:ondrej/php
apt install -y unzip git php8.3 php8.3-mysql php8.3-mbstring php8.3-intl php8.3-dom php8.3-simplexml php8.3-sqlite3 php8.3-pdo
- 安装 Composer:
curl -sS https://getcomposer.org/installer | php
# 验证 Composer 是否正常工作
php composer.phar --version
步骤三:创建 CakePHP 项目:
# 创建新的 CakePHP 项目
php composer.phar create-project --prefer-dist cakephp/app:~5.0 my_cakephp_app
# 进入项目目录
cd my_cakephp_app
步骤四:配置数据库连接
修改 config/app_local.php 文件,配置数据库连接参数:
'Datasources' => [
'default' => [
'host' => '$host',
/*
* CakePHP will use the default DB port based on the driver selected
* MySQL on MAMP uses port 8889, MAMP user will want to uncomment
* the following line and set the port accordingly
*/
'port' => '$port',
'username' => '$user_name',
'password' => '$password',
'database' => '$database_name',
/*
* If not using the default 'public' schema with the PostgreSQL driver
* set it here.
*/
//'schema' => 'myapp',
/*
* You can use a DSN string to set the entire configuration
*/
'url' => env('DATABASE_URL', null),
]
获取数据库地址、端口号、数据库名、用户名和密码参见步骤一。
步骤五:创建模型和表结构
- OceanBase 创建用户表:
CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
email varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
first_name varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
last_name varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
age int(11) DEFAULT NULL,
status varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT 'active',
PRIMARY KEY (id),
UNIQUE KEY idx_email (email),
KEY idx_username (username)
);
- 创建 User 模型 src/Model/Table/UserTable.php:
bin/cake bake model User
步骤六:编写数据库操作代码
创建控制器 src/Controller/UserController.php:
<?php
declare(strict_types=1);
namespace App\Controller;
use Cake\Log\Log;
class UserController extends AppController
{
public function index()
{
$this->autoRender = false;
$this->response = $this->response->withType('application/json');
try {
Log::info('Processing user data...');
$userTable = $this->fetchTable('User');
Log::info('User table created successfully');
// 1. Insert
$user = $userTable->newEmptyEntity();
$userData = [
'username' => 'example_user',
'email' => 'user@example.com',
'age' => 35
];
$user = $userTable->patchEntity($user, $userData);
if ($userTable->save($user)) {
Log::info('Insert succeeded, ID: ' . $user->id);
}
// 2. Read
$foundUser = $userTable->get($user->id);
$userData = $foundUser->toArray();
$userData['created_at'] = 1654857016; // mock timestamp
Log::info('Query result: ' . json_encode($userData, JSON_UNESCAPED_UNICODE));
// 3. Update
$foundUser->age = 36;
if ($userTable->save($foundUser)) {
Log::info('Update succeeded');
}
// 4. Delete
if ($userTable->delete($foundUser)) {
Log::info('Delete succeeded');
}
echo json_encode(['success' => true, 'message' => 'CRUD completed']);
} catch (\Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
}
}
步骤七:运行程序并验证结果
- 启动 CakePHP 内置开发服务器:
bin/cake server -H 0.0.0.0 -p 8765 &
- 使用 curl 测试:
curl -s http://localhost:8765/user
# {"success":true,"message":"CRUD completed"}
- 查看 logs/debug.log 文件,您应该能看到类似以下的日志输出:
2026-03-02 09:38:11 info: Processing user data...
2026-03-02 09:38:11 info: User table created successfully
2026-03-02 09:38:11 info: Insert succeeded, ID: 2
2026-03-02 09:38:11 info: Query result: {"id":2,"username":"example_user","email":"user@example.com","first_name":null,"last_name":null,"age":35,"status":"active","created_at":1654857016}
2026-03-02 09:38:11 info: Update succeeded
2026-03-02 09:38:11 info: Delete succeeded
注意事项
Q1:SHOW INDEXES 输出差异 OceanBase 会把条件表达式在索引元数据里体现为虚拟列名(如 SYS_NC19$),而 MySQL 对应位置为 NULL。若 CakePHP 的 Schema 解析依赖“索引中的 Column_name 必须是表上的真实列名”,则可能因无法识别或错误处理 SYS_NC19$ 而导致解析错误。
Q2:字符集差异 CakePHP 默认使用 utf8_general_ci 字符集,而 OceanBase 默认使用 utf8mb4_general_ci。
Q3:外键命名规则 OceanBase 与 MySQL 的外键命名规则不一致,可能影响 CakePHP 对外键约束的识别。
Q4:未排序查询结果顺序 CakePHP 未指定排序的查询,在 MySQL 中返回升序结果,而在 OceanBase 中可能返回倒序结果。