【问题标题】:PHP Class not found even though module is installed即使安装了模块,也找不到 PHP 类
【发布时间】:2020-01-31 01:52:53
【问题描述】:

我正在尝试使用 mongodb PHP 模块。我已使用 pecl 安装它并将其写入我的 php.ini。呼叫和回显get_loaded_extensions() 正确显示扩展名mongodb。但是,official guide 后面的代码会引发错误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 服务器。

【问题讨论】:

  • 很可能您只在 CLI SAPI 加载的配置文件中加载了此文件,而不是您的 Web SAPI。如果您确实在两者中都加载了它们,您必须记住重新启动您的 Web SAPI 的 php 工作程序以加载扩展。检查正确的SAPI中的phpinfo()以确保。
  • @Sherif 老实说,我不太了解 SAPIS,但在同一网络中的另一台机器上,我可以访问该站点。 phpinfo() 显示正确的 ini 文件,并有一个 mongodb 模块的部分。
  • 您是从命令行执行此操作的,对吗?因此,创建一个包含&lt;?php phpinfo(); 的文件。从您的 Web 浏览器打开它,然后查找 Loaded configuration (php.in) 文件。那就是您要粘贴extension=mongodb.so 的文件。然后重新启动fpm 或apache httpd。
  • @Sherif 在命令行中,我说sudo systemctl start nginx 来启动我的nginx 服务器。现在从另一台机器上,我可以访问服务器上的 php 文件,并在 phpinfo 中查看所有内容都已正确加载。对不起,如果这是一个愚蠢的问题,但是除了命令行我应该在哪里做这个?
  • 如果在 phpinfo() 中一切正常,那么你从哪里得到类不存在的错误?您是从 Web 还是在命令行上运行该脚本?

标签: php mongodb include pear


【解决方案1】:

MongoDB\Client 是一个处理 php mongodb 驱动程序的 php 库,它是您使用 get_loaded_extensions() 看到的 mongodb 扩展名。要使用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";
}

希望这能帮助你理解。

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多