MongoDB PHP 扩展
系统梳理 Linux、Windows 与 macOS 平台安装 MongoDB PHP 扩展(mongodb)的 PECL/源码编译流程、php.ini 配置要点及 TS/NTS 二进制匹配规则,并在离线脚本中验证配置解析与新旧扩展迁移。
学完这一章,你能够
- 系统梳理 Linux、Windows 与 macOS 平台安装 MongoDB PHP 扩展(mongodb)的 PECL/源码编译流程、php.ini 配置要点及 TS/NTS 二进制匹配规则,并在离线脚本中验证配置解析与新旧扩展迁移。
Linux 平台 PECL 与源码编译安装
PHP 访问 MongoDB 需要先安装底层 C 扩展驱动 `mongodb`(历史 PHP 5 时期的 `mongo` 扩展已在 PHP 7+ 中移除)。在 Linux 环境下最便捷的方式是在联网且具备相应权限的终端中执行 `sudo pecl install mongodb` 自动下载并编译安装扩展。
若需要手动从 PECL 官方包(`https://pecl.php.net/package/mongodb`)源码编译以获取最新修复,可解压源码包后依次执行 `phpize`、`./configure`、`make && make install`;如果 PHP 为自定义路径编译安装(如 `/usr/local/php`),则需显式调用对应目录的 `phpize` 并传入 `--with-php-config=/usr/local/php/bin/php-config`。编译结束后终端会打印共享扩展输出目录,随后在 `php.ini` 中配置 `extension_dir` 与 `extension=mongodb.so`(可用 `php -i | grep extension_dir` 或 `php -m` 核对加载路径)。
Windows 预编译 DLL 与 macOS 安装注意事项
在 Windows 平台可直接从 PECL 获取预编译的 `php_mongodb.dll` 二进制包,下载时必须严格匹配 PHP 主次版本、架构(x64/x86)、编译器 ABI(早期资料提及 Apache 对应 VC6、IIS 对应 VC9,现代 PHP 8.x 已统一演进为 VS16/VS17)以及线程安全模式:以 Apache 模块运行选择 Thread Safe(TS),以 CGI/FastCGI/IIS 模式运行选择 Non-Thread Safe(NTS)。将 `php_mongodb.dll` 放入 PHP 的 `ext` 目录并在 `php.ini` 添加 `extension=php_mongodb.dll`(PHP 7.2+ 也可简写 `extension=mongodb`),重启 Web 服务后通过 `phpinfo()` 确认出现 `mongodb` 节区。
在 macOS 上可通过 Homebrew 配合 `autoconf` 与 Xcode Command Line Tools 运行 `pecl install mongodb` 编译安装;若使用 XAMPP/MAMP 集成环境,需调用对应环境自带的 `pecl` 可执行文件(注意早期教程中 `pecl install mongo` 安装的是已废弃的 PHP 5 旧扩展,PHP 7/8 环境务必改为 `pecl install mongodb`),最后同样在 `php.ini` 中启用 `extension=mongodb.so`。
离线验证 Linux php.ini 扩展加载配置、Windows TS/NTS DLL 选型与旧 mongo 扩展迁移
"""Offline MongoDB PHP extension installation & php.ini configuration verifier."""
import json
from pathlib import Path
import tempfile
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def parse_php_ini_extensions(ini_text):
ext_dir = None
extensions = []
for raw in ini_text.splitlines():
line = raw.strip()
if not line or line.startswith(";"):
continue
if line.startswith("extension_dir"):
ext_dir = line.split("=", 1)[1].strip().strip('"')
elif line.startswith("extension"):
extensions.append(line.split("=", 1)[1].strip().strip('"'))
return {"extension_dir": ext_dir, "extensions": extensions}
def select_windows_dll(sapi_mode, arch, php_minor):
ts_flag = "ts" if sapi_mode == "apache_module" else "nts"
return {
"sapi": sapi_mode,
"thread_safety": ts_flag,
"package_artifact": f"php_mongodb-{php_minor}-{ts_flag}-{arch}.zip",
"dll_name": "php_mongodb.dll",
"ini_directive": "extension=php_mongodb.dll",
}
def main():
with tempfile.TemporaryDirectory() as tmp:
linux_ini = Path(tmp) / "php-linux.ini"
linux_ini.write_text(
"extension_dir=/usr/lib/php/extensions/no-debug-non-zts-20230831/\n"
"extension=mongodb.so\n",
encoding="utf-8",
)
parsed_linux = parse_php_ini_extensions(linux_ini.read_text(encoding="utf-8"))
# Case 1: Linux PECL / phpize build pipeline & php.ini extension verification
build_steps = ["phpize", "./configure --with-php-config=/usr/local/php/bin/php-config", "make", "make install"]
c1_actual = {
"pecl_package": "mongodb",
"build_steps": build_steps,
"ini_parsed": parsed_linux,
}
c1_expected = {
"pecl_package": "mongodb",
"build_steps": build_steps,
"ini_parsed": {
"extension_dir": "/usr/lib/php/extensions/no-debug-non-zts-20230831/",
"extensions": ["mongodb.so"],
},
}
# Case 2: Windows TS (Apache module) vs NTS (CGI/FastCGI/IIS) DLL selection
win_apache = select_windows_dll("apache_module", "x64", "8.4")
win_cgi = select_windows_dll("cgi_fastcgi", "x64", "8.4")
c2_actual = {
"apache_ts": win_apache["thread_safety"],
"cgi_nts": win_cgi["thread_safety"],
"dll_name": win_apache["dll_name"],
"ini_directive": win_cgi["ini_directive"],
}
c2_expected = {
"apache_ts": "ts",
"cgi_nts": "nts",
"dll_name": "php_mongodb.dll",
"ini_directive": "extension=php_mongodb.dll",
}
# Case 3: macOS PECL / XAMPP legacy `mongo` vs modern `mongodb` extension migration contract
c3_actual = {
"legacy_php5_ext": "mongo",
"modern_php7_php8_ext": "mongodb",
"macos_ini_directive": "extension=mongodb.so",
"legacy_removed_in_php7": True,
}
c3_expected = {
"legacy_php5_ext": "mongo",
"modern_php7_php8_ext": "mongodb",
"macos_ini_directive": "extension=mongodb.so",
"legacy_removed_in_php7": True,
}
cases = [
{
"name": "linux_pecl_source_build_and_ini",
"summary": "Verify Linux PECL/phpize compilation flow and php.ini extension_dir + extension=mongodb.so parsing.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "windows_ts_vs_nts_dll_selection",
"summary": "Verify Windows Thread Safe (Apache module) vs Non-Thread Safe (CGI/FastCGI) DLL selection and ini entry.",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "macos_ext_and_legacy_mongo_migration",
"summary": "Verify macOS extension=mongodb.so directive and migration from removed PHP 5 'mongo' to 'mongodb'.",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在离线脚本中验证 php.ini extension_dir/extension 解析、Apache TS 与 CGI NTS DLL 包选型规则以及 legacy mongo 到 modern mongodb 的迁移标识。
所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
当前源码 SHA256:e285d5ea95929409c92624c882400a382f439532f5fe37c356474caed448f4fe
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
ZIP SHA256:1029cd3d5f51a5e350dfcb8336db704464f52138c33803aa3955e67eb226659e
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Windows 上以 PHP-FPM / FastCGI 模式运行 PHP 8.4 时,应该下载 TS 还是 NTS 版本的 php_mongodb.dll?
展开参考解答
应选择 Non-Thread Safe(NTS)且与 PHP 8.4 架构(如 x64)和编译器版本(VS16/VS17)完全匹配的 php_mongodb.dll;TS 仅用于多线程模块模式(如 Apache mod_php)。