PHP, MongoDB and MAMP

Wife is out, kids asleep, perfect let’s code. Let’s do something I’ve never done, like write a RESTful endpoint using slim.php and mongoDB. How hard can that be? Wait, what? PHP doesn’t do mongoDB out of the box? K, cool, I gots this. Install driver into MAMP…


pecl install mongo
...
...
...

1 error generated.
make: [php_mongo.lo] Error 1

Sad trombone. Search The Googles


About 1,980 results (0.47 seconds) 

Took me most of the night to find the answer I need so here we go. This tutorial assumes you are using MAMP, have MAMP’s version of PHP in your $PATH, have MongoDB installed and running, have Xcode Developer tools installed and are not completely useless in the command line. If any of these are not true, refer to The Googles. If any of these assumptions confuse you or make you feel uncomfortable, then you are a Windows user and likely got here by mistake.

  1. Download the version of PHP you are using in MAMP from the PHP releases. For me, using MAMP 3.0.6, that happens to be PHP 5.5.14.

  2. Make an include folder inside of your current MAMP php version…

    
    mkdir -vp /Applications/MAMP/bin/php/php5.5.14/include
    
  3. Untar the downloaded package…
    
    tar zxvf ~/Downloads/php-5.5.14.tar.gz /Applications/MAMP/bin/php/php5.5.14/include/
    
  4. Change directory…
    
    cd /Applications/MAMP/bin/php/php5.5.14/include/
    
  5. Rename the php directory…
    
    mv php-5.5.14 php
    
  6. Configure the sources…
    
    cd php
    ./configure
    
  7. Ok awesome, now using MAMPs install of pecl (just to be anal)…
    
    cd /Applications/MAMP/bin/php/php5.5.14/bin
    sudo ./pecl install mongo
    
  8. Now edit MAMPs php.ini
    
    vim /Applications/MAMP/bin/php/php5.5.14/conf/php.ini
    

    find where the extensions are loaded (look for “; Extensions”) and add…

    
    extension-mongo.so
    
  9. Restart the MAMP servers.

  10. Test with the following code in a browser…

    
    <?php
    
        // Show PHP errors (during development only)
        error_reporting(E_ALL | E_STRICT);
        ini_set("display_errors", 2);
    
        // Create a Mongo conenction
        $mongo = new MongoClient("mongodb://localhost");
    
        // Choose the database and collection
        $db = $mongo->my_db_name;
        $coll = $db->my_collection_name;
    
        // Same a document to the collection
        $coll->save(array(
            "name" => "Jack Sparrow",
            "age" => 34,
            "occupation" => "Pirate"
        ));
    
        // Retrieve the document and display it
        $item = $coll->findOne();
    
        echo "My name is " . $item['name'] . ". I am " . $item['age'] . " years old and work full-time as a " . $item['occupation'] . ".";

Sources (to name a few): stackoverflow, Luke Peters

 

Adam Merrifield

 

Leave a Reply