【问题标题】:Can you use PHP to connect with Azure CosmosDB?可以使用 PHP 连接 Azure CosmosDB 吗?
【发布时间】:2018-02-07 19:28:56
【问题描述】:

我目前正在构建一个 web 应用程序,我需要使用 CosmosDB。我一直在尝试寻找 PHP 的连接脚本,但似乎找不到直接的答案。

所以我的问题是,我可以使用 PHP 连接 Azure Cosmos DB 吗?我有一个来自 Unity 的脚本,它将数据作为 JSON 文件解析到 CosmosDB,但是我可以使用 PHP 连接到 Azure 吗?什么方法最适合访问数据?

如果是这样,是否有我需要的 API 或某个连接脚本?我愿意接受建议,但直接回答会很有帮助,因为我目前正在使用 Bluehost 的共享主机,所以我坚持使用典型的 LAMP 配置。

顺便说一句,如果你觉得这篇文章很熟悉,那是因为我半小时前也在 Reddit 上发布了这篇文章。

谢谢!

【问题讨论】:

    标签: php azure azure-cosmosdb


    【解决方案1】:

    如果要将 Azure Cosmos DB 用作 MongoDB,可以使用其 MongoDB Api 和“官方”MongoDB 库。

    获取连接字符串

    要了解连接字符串,您可以按照此处的文档进行操作:https://docs.microsoft.com/es-es/azure/cosmos-db/connect-mongodb-account#GetCustomConnection

    从那里:

    1. 在 Internet 浏览器中,登录 Azure 门户。
    2. 在 Azure Cosmos DB 边栏选项卡中,选择 MongoDB 帐户的 API。
    3. 在帐户刀片的左侧窗格中,单击连接字符串。
    4. “连接字符串”边栏选项卡打开。它包含使用 MongoDB 驱动程序连接到帐户所需的所有信息,包括预先构建的连接字符串。

    Azure Cosmos DB 支持标准 MongoDB 连接字符串 URI 格式,但有几个特定要求: Azure Cosmos DB 帐户需要通过 SSL 进行身份验证和安全通信。所以,连接字符串的格式是:

    mongodb://username:password@host:port/[database]?ssl=true
    

    此字符串的值在前面显示的连接字符串刀片中可用:

    • 用户名(必填):Azure Cosmos DB 帐户名。
    • 密码(必填):Azure Cosmos DB 帐户密码。
    • 主机(必需):Azure Cosmos DB 帐户的 FQDN。
    • 端口(必填):10255。
    • 数据库(可选):连接使用的数据库。如果未提供数据库,则默认数据库为“test”。
    • ssl=true(必需)

    例如,考虑连接字符串边栏选项卡中显示的帐户。一个有效的连接字符串是:

    mongodb://contoso123:0Fc3IolnL12312asdfawejunASDF@asdfYXX2t8a97kghVcUzcDv98hawelufhawefafnoQRGwNj2nMPL1Y9qsIr9Srdw==@contoso123.documents.azure.com:10255/mydatabase?ssl=true
    

    访问数据

    对于当前在 PHP 中的使用,您可以使用 http://php.net/manual/en/mongodb.tutorial.library.php

    通过运行安装库:

    $ composer require mongodb/mongodb
    

    举个例子,这是将文档插入演示数据库的 beers 集合的方式:

    <?php
    require 'vendor/autoload.php'; // include Composer's autoloader
    
    $client = new MongoDB\Client("mongodb://localhost:27017");
    $collection = $client->demo->beers;
    
    $result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
    
    echo "Inserted with Object ID '{$result->getInsertedId()}'";
    ?>
    

    【讨论】:

      【解决方案2】:

      克隆https://github.com/Azure-Samples/azure-cosmos-db-graph-php-getting-started.git 然后在 connect.php 中填写您的凭据

      $db = new Connection([
          'host' => '<your_server_address>.graphs.azure.com',
          'username' => '/dbs/<db>/colls/<coll>',
          'password' => 'your_primary_key'
          ,'port' => '443'
          // Required parameter
          ,'ssl' => TRUE
      ]);
      

      【讨论】:

        【解决方案3】:

        很遗憾,Azure CosmosDB (DocumentDB API) 目前没有官方的 PHP SDK。

        您可以使用REST APIAzureDocumentDB-PHP 等社区驱动程序与CosmosDB 进行交互。

        【讨论】:

        • AzureDocumentDB-PHP Wrapper 是否适用于 Laravel? @Aaron Chen
        猜你喜欢
        • 2023-01-09
        • 1970-01-01
        • 1970-01-01
        • 2021-09-11
        • 2011-08-09
        • 2020-03-16
        • 2018-05-07
        • 2015-05-16
        • 1970-01-01
        相关资源
        最近更新 更多