首页 > 解决方案 > 即使安装了模块,也找不到 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 服务器,如果这很重要的话。

标签: phpmongodbincludepear

解决方案


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";
}

希望这能帮助你理解。


推荐阅读