Recently we upgraded to php7 in our local environment, and most things worked straight away without any changes. Going from php 5.5 to php 7 seemed to work flawlessly with most of our code, as we have been strictly sticking to php standards in coding for quite some time, so the backwards compatibility seemed to be great.

Our projects are running with Zend Framework. Some of our older ones with Zend Framework 1 but our current projects all are using ZF2 as the code base.

Then suddenly a task I had running in the background failed, and it was apparent that the MongoDb wasn’t working correctly in a project that we had running. My first thought was that I didn’t have MongoDb installed in the new Xampp that I had installed on the computer, however after looking over things, I found that we needed to use a different library for MongoDb in php with php7.

Bring in the MongoDb PHP Library.

To install this use

pecl install mongodb

or install it manually. You will need to find the instructions.

Now when it came to the code side of things we previously had this

use MongoClient;

use MongoDate

use MongoRegex;

which we can now change to

use \MongoDB\Client as MongoClient;
use \MongoDB\BSON\UTCDateTime as MongoDate;
use \MongoDB\BSON\Regex as MongoRegex;

A couple of things that we found however was that the MongoDate was a bit different in the php library.

We also found that using 32 bit instead of 64 bit had issues with Dates.

So we ended up using something like this

if (PHP_INT_SIZE === 4) {
    $start = $start * 1000;
}

What this does? It detects if we are running 32 bit and if it is then multiply the timestampt by 1000

So here is our code

$start = strtotime($date . " 00:00:00");
$end = strtotime($date . " 23:59:59");
if (PHP_INT_SIZE === 4) {
    $start = $start * 1000;
    $end = $end * 1000;
}
$start = new MongoDate($start);
$end = new MongoDate($end);

$results = iterator_to_array($this->collection->find(array(“date” => array(‘$gt’ => $start, ‘$lte’ => $end))));

using MongoRegex which is now \MongoDb\BSON\MongoRegex we can now search using the following.

public function searchDomains($term)
{
    $results = iterator_to_array($this->collection->find(array('name' => array('$regex' => new MongoRegex('' . $term . '', 'i')))));
    return $results;
}

Once I had read up on it, and worked out the differences it wasn’t that hard to work with the new MongoDb library. I’m sure there’s a lot more to learn though, which I’m keen to hear about.

Please feel free to comment on any other great resources for mongoDb upgrade to the php library.