Skip to content

Building PHP MongoDB Driver

aborkar-ibm edited this page Mar 2, 2022 · 60 revisions

Building the PHP Driver for MongoDB

Below versions of PHP Driver for MongoDB are available in respective distributions at the time of creation of these build instructions:

  • Ubuntu 18.04 has 1.3.4
  • Ubuntu 20.04 has 1.6.1
  • Ubuntu 21.10 has 1.9.0+1.7.5

The instructions provided below specify the steps to build PHP Driver for MongoDB version 1.12.1 on Linux on IBM Z for following distributions:

  • RHEL (7.8, 7.9, 8.2, 8.4, 8.5)
  • SLES (12 SP5, 15 SP3)
  • Ubuntu (18.04, 20.04, 21.10)

General Notes:

  • When following the steps below please use a standard permission user unless otherwise specified .
  • A directory /<source_root>/ will be referred to in these instructions, this is a temporary writable directory anywhere you'd like to place it.

Step 1 : Build and Install PHP driver for MongoDB

1.1) Install dependencies

export SOURCE_ROOT=/<source_root>/
  • RHEL (7.8, 7.9)

    sudo yum install -y cyrus-sasl-devel gcc make openssl-devel pkgconfig
    • Install PHP Enable Software Collections: (Only for RHEL)

    MongoDB Driver PHP requires PHP 7.0 or higher. This is available on RHEL 7.x via the 'software collections' packaging system. You can find out more about software collections here: https://www.softwarecollections.org/en/.

    These commands will enable PHP 7.2. The changes are not persistent and these commands will need to be re-run every time a new terminal session is started.

    sudo subscription-manager repos --enable=rhel-7-server-for-system-z-rhscl-rpms
    sudo yum install -y rh-php72 rh-php72-php-devel
    source /opt/rh/rh-php72/enable
  • RHEL (8.2, 8.4, 8.5)

    sudo yum install -y cyrus-sasl-devel gcc make openssl-devel pkgconfig php php-devel php-json php-pear
  • SLES 12 SP5

    sudo zypper install -y cyrus-sasl-devel gcc libopenssl-devel make php72 php72-devel php72-json php72-openssl pkg-config which gawk
  • SLES 15 SP3

    sudo zypper install -y cyrus-sasl-devel gcc libopenssl-devel make php7 php7-devel php7-json php7-openssl pkg-config gawk
  • Ubuntu (18.04, 20.04, 21.10)

    sudo apt-get update
    sudo apt-get install -y libsasl2-dev libssl-dev php php-dev pkg-config

1.2) Install MongoDB PHP driver

  • RHEL

    sudo env PATH=$PATH pecl install mongodb-1.12.1
  • SLES and Ubuntu

    sudo pecl install mongodb-1.12.1

    Note:

    • If you encounter this error: Connection to 'pecl.php.net:443' failed: Unable to find the socket transport "ssl", please run this command prior to running pecl:

      sudo sed -i 's|$PHP -C -n -q |$PHP -C -q |' `which pecl`
    • The MongoDB PHP driver requires libbson and libmongoc, so it will use bundled versions (1.17.4) of the libraries, if they aren't present.

1.3) Enable PHP extension

echo -e "\n; MongoDB PHP driver\nextension=mongodb.so" | sudo tee -a `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`

Step 2: Testing (Optional)

The example code section given below is used to perform a basic test to ensure that the MongoDB PHP Driver is working as expected, and can connect and query a MongoDB server. Instructions to install MongoDB and MongoDB Shell (mongosh) can be found on their official website here.

2.1) Start MongoDB

To run this test, MongoDB must be running on the default port, 27017. The following commands are an example of how to start a MongoDB server and then connect to it with the client shell.

Issue the following command to start mongod and to check if it is up, connect to it with the MongoDB shell.

mongosh --host <hostname or IP address> --port 27017

The output should be similar to:

Current Mongosh Log ID:	61a4e5f5f2d1071b57593ed7
Connecting to:		mongodb://<hostname or IP address>:27017/?directConnection=true
Using MongoDB:		5.0.2
Using Mongosh:		1.0.6
...
test>

2.2) The test code

Create a file named test.php with the content shown below. If you are connecting to a remote server then you need to substitute the localhost with the hostname or IP address of the MongoDB server.

<?php

   // Config
   $dbhost = 'localhost';
   $dbname = 'ibm_test_db';
   $collection = 'mongodb_php_client';
   $test_msg = 'test message';

   $manager = new MongoDB\Driver\Manager("mongodb://$dbhost");

   /* The driver connects to the database server lazily, so Manager::getServers()
    * may initially return an empty array. */
   var_dump($manager->getServers());

   $command = new MongoDB\Driver\Command(['ping' => 1]);
   $manager->executeCommand('db', $command);

   var_dump($manager->getServers());

   $bulk = new MongoDB\Driver\BulkWrite;
   $bulk->insert(['x' => 1]);
   $bulk->insert(['x' => 2]);
   $bulk->insert(['x' => 3]);

   $manager->executeBulkWrite('db.collection', $bulk);

   $filter = ['x' => ['$gt' => 1]];
   $options = [
       'projection' => ['_id' => 0],
       'sort' => ['x' => -1],
   ];

   $query = new MongoDB\Driver\Query($filter, $options);
   $cursor = $manager->executeQuery('db.collection', $query);

   foreach ($cursor as $document) {
       var_dump($document);
   }

   $command = new MongoDB\Driver\Command(['ping' => 999]);

   try {
       $cursor = $manager->executeCommand('admin', $command);
   } catch(MongoDB\Driver\Exception $e) {
       echo $e->getMessage(), "\n";
       exit;
   }

   /* The ping command returns a single result document, so we need to access the
    * first result in the cursor. */
   $response = $cursor->toArray()[0];

   var_dump($response);
?>

Execute the test script by:

php test.php

Executing the script should produce output similar to this:

array(1) {
  [0]=>
  object(MongoDB\Driver\Server)#4 (10) {
    ["host"]=>
    string(9) "localhost"
    ["port"]=>
    int(27017)
    ["type"]=>
    int(1)
    ["is_primary"]=>
    bool(false)
    ["is_secondary"]=>
    bool(false)
    ["is_arbiter"]=>
    bool(false)
    ["is_hidden"]=>
    bool(false)
    ["is_passive"]=>
    bool(false)
    ["last_hello_response"]=>
    array(10) {
      ["ismaster"]=>
      bool(true)
      ["maxBsonObjectSize"]=>
      int(16777216)
      ["maxMessageSizeBytes"]=>
      int(48000000)
      ["maxWriteBatchSize"]=>
      int(100000)
      ["localTime"]=>
      object(MongoDB\BSON\UTCDateTime)#3 (1) {
        ["milliseconds"]=>
        string(13) "1629821518626"
      }
      ["logicalSessionTimeoutMinutes"]=>
      int(30)
      ["minWireVersion"]=>
      int(0)
      ["maxWireVersion"]=>
      int(7)
      ["readOnly"]=>
      bool(false)
      ["ok"]=>
      float(1)
    }
    ["round_trip_time"]=>
    int(0)
  }
}
object(stdClass)#7 (1) {
  ["x"]=>
  int(3)
}
object(stdClass)#8 (1) {
  ["x"]=>
  int(2)
}
object(stdClass)#9 (1) {
  ["ok"]=>
  float(1)
}

References:

Clone this wiki locally