【问题标题】:How to properly convert MongoDB BSON into PHP Object如何正确地将 MongoDB BSON 转换为 PHP 对象
【发布时间】:2016-04-30 04:36:52
【问题描述】:

我希望你们能帮我解决这个问题:

首先要做的事情 - 我正在使用以下版本/库:

我正在尝试转换从数据库中取出的 BSON 数组,以便在我的项目中使用。

据我了解,MongoDB 的一大机遇是在一个集合中拥有不同的组织数据。 就像在这个例子中(其中只有一个对象有“描述”标签:

JSON 文档:

{
    enumbers ":[ {
        "id": "84",
        "enumber": "E 472 b",
        "name": "Milchs\u00e4ureester von Mono- und Diglyceriden von Speisefetts\u00e4uren"
    }, {
        "id": "198",
        "enumber": "E 407",
        "name": "Carrageen",
        "description": "Testdescription",
    }, {
        "id": "293",
        "enumber": "E 941",
        "name": "Stickstoff"
    }]
}

我正在使用以下代码访问数据库:

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$collection = new MongoDB\Collection($manager, "test", "items");
$document = $collection->findOne(["id" => '5']);
$product= new Product($document);

到这里为止都可以正常工作。

use MongoDB\Model\BSONArray;
use MongoDB\Model\BSONDocument;
class Product
public function __construct(BSONDocument $data)
{


    foreach ($data as $part){
        try{
        $this->setId($part->id);
        $this->setEnumber($part->id);
        $this->setName($part->name);
        --------------------------------------
        $this->setDescription($part->description);
        --------------------------------------
        }catch (\Exception $e){
            echo $e;
        }

    }

    echo "-------------------------------------------------".PHP_EOL;

}

现在是“$this->setDescription($part->description);”抛出异常:

ErrorException: Trying to get property of non-object

未定义“描述”标签的地方。

其实我希望它在不存在的地方返回 null。

我如何正确捕捉到某些数据集可能有也可能没有这个标签?

希望您能帮助我并感谢您的阅读:)

【问题讨论】:

    标签: php mongodb exception bson


    【解决方案1】:

    我发现我试图在我的函数中访问“太深”的一层。 当我尝试访问时

    $this->setDescription($data->description);
    

    我可以检查它是否已设置:

    if (isset($data->name)) $this->setName($data->name);
    

    有效。

    我以为我已经尝试过了,但没有结果 - 但我认为写一篇应有的论文会导致过度阅读。

    【讨论】:

    • 我不会再使用这个概念了。我现在会使用 Hydrator(-Concept)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    相关资源
    最近更新 更多