How to use MongoDB driver of PHP in an iron worker task?

269 views Asked by At

I'm using iron.io and its worker tasks for a background process. My code is fairly simple, just like:

<?php
require 'vendor/autoload.php';

$uri = "my_connection_string";
$client = new MongoClient($uri);
:
:

composer.json is like:

{
    "require": {
        "iron-io/iron_worker": "2.0.4",
        "wp-cli/php-cli-tools": "~0.10.3"
    }
}

Then I first install all dependencies,

docker run --rm -it -v "$PWD":/worker -w /worker iron/php:dev composer install

compress my code,

zip -r worker.zip .

upload it,

iron --env dev worker upload --name task-name -zip ./worker.zip iron/php:dev php ./worker.php

then this error output.

PHP Fatal error:  Class 'MongoClient' not found in /mnt/task/worker.php on line xxx

I also tried MongoDB\Driver\Manager, MongoDB\Driver\Client, the same error occurs. When I tried running php -m, it shows:

[PHP Modules]
Core
curl
date
ereg
fileinfo
filter
hash
json
libxml
mbstring
mysqlnd
pcre
readline
Reflection
session
SimpleXML
SPL
standard
tokenizer
xmlwriter

[Zend Modules]

It looks even MongoDB extension is not installed, while they say it's installed. http://dev.iron.io/worker/languages/php/

Am I missing something? How can I use MongoDB driver in PHP with iron worker?

1

There are 1 answers

0
Norio Akagi On

For those who may be in the same situation as I was, this happens because Iron.io now integrates Docker and we have to specify an image we use when running our code, but iron/php image doesn't include any additional middlewares they used to support.

So we have to write our own DockerFile to install MongoDB or MySQL or whatever necessary middleware & software we need.

As for MongoDB, this is an example of a Dockerfile.

iron/php:5.6.14
RUN apk update
RUN apk upgrade
RUN apk add alpine-sdk
RUN apk add zlib-dev
RUN apk add curl
RUN apk add bash
RUN apk add perl
RUN apk add re2c
RUN apk add pcre-dev
RUN apk add openssl-dev
RUN apk add php-dev autoconf
RUN git clone https://github.com/mongodb/mongo-php-driver.git
WORKDIR ./mongo-php-driver
RUN which php
RUN git submodule sync && git submodule update --init
RUN phpize
RUN ./configure
RUN make all -j 5
RUN make install
RUN echo 'extension=mongo.so' >> /etc/php.ini

Please note that this isn't optimized at all in terms of an image size.

I think it's very helpful if Iron.io'd provide such images.