php - 即使安装了模块,也找不到 PHP 类
问题描述
我正在尝试使用 mongodb PHP 模块。我已使用 pecl 安装它并将其写入我的 php.ini。呼叫和回显get_loaded_extensions()
正确显示分机mongodb
。但是,我遵循官方指南的代码会引发错误class MongoDB\Client not found
。我该如何解决?我是否需要以某种方式首先包含模块?
我的代码:
<?php
var_dump(get_loaded_extensions());
$client = new MongoDB\Client(
'mongodb+srv://<username>:<password>@<cluster-address>/test?retryWrites=true&w=majority'
);
我在安装了 rasbian lite 的树莓派上托管了一个 nginx 服务器,如果这很重要的话。
解决方案
MongoDB\Client
是一个处理 php mongodb 驱动程序的 php 库,它是mongodb
您看到的扩展get_loaded_extensions()
。要使用MongoDB\Client
该类,您需要下载名为mongodb/mongodb的库。
首先在您的项目根目录中创建一个您喜欢的名称的文件夹,例如,mongodb_test
在我们的例子中;现在创建一个名为composer.json的文件并将以下代码放入其中:
{
"require": {
"mongodb/mongodb": "^1.2"
}
}
然后在命令行工具上运行以下命令:
php composer.phar install
或者如果 composer 是全局安装的,则使用以下命令
composer install
接下来,在同一目录/文件夹中创建一个具有任何名称的新文件,并将以下代码放入本地主机中进行测试。
<?php
// Notice here. This is a must that you're missing
require 'vendor/autoload.php';
// Create client object
$client = new MongoDB\Client("mongodb://localhost:27017");
// Gets collection
$collection = $client->demo->beers;
// Inserts data
$result = $collection->insertOne(['name' => 'Hinterland', 'brewery' => 'BrewDog']);
echo 'Inserted with Object ID: ' . $result->getInsertedId() . '<br>';
// Fetches data
$result = $collection->find(['name' => 'Hinterland']);
// Iterates over data
foreach ($result as $entry) {
echo $entry['_id'], ': ', $entry['name'], "\n";
}
希望这能帮助你理解。
推荐阅读
- swift - 如何塑造类似 Ipad 的 Popover 的方向?
- c# - 转换格式时magickimage.net(C#)图像饱和度?
- react-native - 无法运行 Expo 生成的 .apk
- java - 是否从 Spring 5 中删除了 GlobalSession 范围的 bean?为什么?
- yaml - 如何引用 yaml 文件中的值?
- centos7 - 通过mulval生成攻击图
- netsuite - 提交事件后如何获得承诺的项目数量?
- javascript - 条形图不显示
- javascript - 将对象数组转换为对象
- python - 删除除python“列表”中指定的少数文件和目录之外的所有文件和目录