Skip to content

Building PHP MongoDB Driver

aborkar-ibm edited this page Aug 11, 2020 · 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

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

  • RHEL (7.6, 7.7, 7.8, 8.1, 8.2)
  • SLES (12 SP5, 15 SP1)
  • Ubuntu (18.04, 20.04)

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.6, 7.7, 7.8)

    sudo yum install -y which autoconf automake bison cyrus-sasl-devel gcc libtool libxml2-devel make openssl-devel pkgconfig tar wget
    • Install PHP Enable Software Collections: (Only for RHEL)

    MongoDB Driver PHP requires PHP 5.6 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.1, 8.2)

    sudo yum install -y which autoconf automake cyrus-sasl-devel gcc libtool libxml2-devel make openssl-devel pkgconfig tar wget php php-devel php-json php-pear
  • SLES (12 SP5, 15 SP1)

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

    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.8.0
  • SLES and Ubuntu

    sudo pecl install mongodb-1.8.0

    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.16.0) 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 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.

mongod > /tmp/mongodb.log &
mongo --host localhost --port 27017
MongoDB shell version v4.0.6
connecting to: mongodb://localhost:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("2346a634-5bd8-4047-8927-fd5a09a88878") }
MongoDB server version: 4.0.6
Welcome to the MongoDB shell.
...
>

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(0) {
}
array(1) {
  [0]=>
  object(MongoDB\Driver\Server)#3 (10) {
    ["host"]=>
    string(21) "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_is_master"]=>
    array(11) {
      ["ismaster"]=>
      bool(true)
      ["maxBsonObjectSize"]=>
      int(16777216)
      ["maxMessageSizeBytes"]=>
      int(48000000)
      ["maxWriteBatchSize"]=>
      int(100000)
      ["localTime"]=>
      object(MongoDB\BSON\UTCDateTime)#4 (1) {
        ["milliseconds"]=>
        string(13) "1579636821224"
      }
      ["logicalSessionTimeoutMinutes"]=>
      int(30)
      ["connectionId"]=>
      int(15039)
      ["minWireVersion"]=>
      int(0)
      ["maxWireVersion"]=>
      int(8)
      ["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)#5 (1) {
  ["ok"]=>
  float(1)
}

References:

MongoDB PHP Driver Overview - https://docs.mongodb.com/ecosystem/drivers/php/
MongoDB PHP Driver Documentation - https://secure.php.net/manual/en/set.mongodb.php
MongoDB PHP Driver GitHub - https://github.com/mongodb/mongo-php-driver

Clone this wiki locally