Getting started with MongoDB, MongoLab, PHP and OpenShift

Overview

MongoDB is a NoSQL document storage database that has quickly become one of the default databases that developers use when creating new applications. The ease of use of the database system and the JSON document storage implementation are just a few of the reasons that developers are flocking to this NoSQL database. With a plethora of drivers available for most programming languages, getting up and running with this database is often a trivial task. Is this blog post, we will show the steps for deploying a MongoDB instance using the popular MongoLab database hosting provider and then integrating that database with a PHP application that is deployed on OpenShift.

Signing up for a MongoLab account

MongoLab offers free MongoDB instances for developers to try their service in order to get a good understanding of the platform in which they host your database. Signing up is quick and easy as you only need to provide an email address and password. In order to sign up, head over to the MongoLab website and click the sign up button.

After you have created an account, you will be presented with a screen to create your first database.

Create a MongoDB database on OpenShift picture

In the above image, I created a database with the name of mydb and selected Amazon EC2 as my hosting provider. I chose EC2 East as that is where OpenShift Online gears are located by default. This will provide the lowest latency possible between my application and the database.

I also created a database user for my application to use.

After the database has been created, you can view information about the database as well as perform administration tasks such as user management and backup scheduling by using their web console. You will also be provided with the connection URL for your database. Make a note of the connection URL as we will be using it later in the blog post.

manager mongodb database on openshift picture

Testing the connection

Now that you have the connection URL for your MongoDB database that is hosted by MongoLab, we can verify that everything is working correctly by connection to the remote database from our local machine.

Note: In order to test the connection from your local machine, you will need to the mongo client installed locally. If you do not have this installed, you can skip this step.

Connection string for MongoDB on OpenShift picture

Creating an OpenShift Online account

Step 1: Create an OpenShift Account

If you don’t already have an OpenShift account, head on over to the website and signup. It is completely free and Red Hat gives every user three free Gears on which to run your applications. At the time of this writing, the combined resources allocated for each user is 1.5 GB of memory and 3 GB of disk space.

Step 2: Install the client tools on your machine

Note: If you would rather watch a screencast of this step, check out the following videos where I demo how to install the client tools.

The OpenShift client tools are written in a very popular programming language called Ruby. With OSX 10.6 or later and most Linux distributions, ruby is installed by default so installing the client tools is a snap. Simply issue the following command on your terminal application:

sudo gem install rhc

Step 3: Create an OpenShift application

Now that we have an OpenShift account and the client tools installed, lets get started building an application to use our MongoDB instance. The first thing we need to do is create a gear that will hold our application code and database. I will be using the command line tools that we installed in step 2, but you can perform the same action via the web console or using our IDE integration.

$ rhc app create mymongoapp php-5.3

This will create an application container for us, called a gear, and setup all of the required SELinux policies and cgroup configuration. OpenShift will also setup a private git repository for you and propagate your DNS out world wide. This whole process should take about 30 seconds.

Once the application has been has been created, you can verify that it is working properly by loading the following URL in your web browser:

http://{yourAppName}-{yourNamespace}.rhcloud.com

For example, if you named your application mymongoapp, like the example above and if your namespace or domain is mycoolapps, the url would be:

http://mymongoapp-mycoolapps.rhcloud.com

Adding PHP and the CodeIgniter Framework

In order to modify the existing PHP application that was created by default with support for CodeIgniter, you can issue the following command:

cd mymongoapp
git remote add upstream -m master git://github.com/openshift/CodeIgniterQuickStart.git
git pull -s recursive -X theirs upstream master

Note: You can also download and push the CI framework yourself but I have provided the above git repository as a convenience.

Adding MongoDB support to CodeIgniter

Now that we have an application created, mongodb added, and CodeIgniter ready to go, the next step is to add mongodb support to the framework. By default, OpenShift already includes a php mongodb driver so you don't have to worry about that aspect.

For this blog post, I am going to use a mongodb library written by Alex Bilbie, which is available on github.

Getting up and running with this library is pretty straightforward. Simply add the file Mongo_db.php to your /application/libraries folder and the file mongodb.php to your /application/config folder.

Once you have copied over those files, edit the mongodb.php file located in the mymongoapp/php/application/config directory and make the following changes using the information provided to you by MongoLab:

$config['mongo_host'] = 
$config['mongo_port'] = 
$config['mongo_db'] = 
$config['mongo_user'] = 
$config['mongo_pass'] =

Once you have finished adding the files and modifying the configuration file, add the files to git and commit the changes.

$ cd mymongoapp
$ git add .
$ git commit -am "Adding mongodb library"
$ git push

Creating a Model, View, and Controller

If you are new to programming you may not have even heard of the MVC design pattern. MVC stands for Model-View-Controller and is a design pattern whose fundamental principle is that developers should separate the presentation from the business logic of an application. Many frameworks employ MVC at the core of the framework and CodeIgniter is no exception.

Create the Model

Models are PHP classes that are designed to work with information in your database. For example, let's say you want to use CodeIgniter to create a simple user account and then search for users at a later point. Create a file under the mymongoapp/php/application/models directory and name the file usermodel.php. The source code for that file should look like this:

<?php

    class UserModel extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    function getUser($username) {
        $this->load->library('mongo_db');

        $user = $this->mongo_db->get_where('users', array('username' => $username));
        return $user;
    }

    function createUser($username, $password) {
        $this->load->library('mongo_db');
        $user = array('username' => $username,
            'password' => $password);

        $this->mongo_db->insert('users', $user);
    }

    }

?>

Let’s examine the createUser function that we defined above.  The first thing we decide is that any person calling this API method will be expected to provide a username and a password for the user account that is to be created.  Note that since this is just a simple example that we are not performing any validation on the createUser function.  Typically you would do some routine checks to ensure the user doesn’t already have an account or to ensure the username and password conform to your password length standards.

The first code snippet in the function loads the mongodb library that we included in our application above.  This call will search for a php library with the specified name in the libraries directory which is located under the application directory.

We then create a user array that will hold the data we want to insert into our mongodb database.  In this case, we are just using the parameters that were passed in to the function call.

The next statement is where we actually insert the data into our database:

$this->mongo_db->insert('users', $user);

This code says to use the mongo_db library that we loaded and perform an insert on the users collection with the $user array acting as the data.  Keep in mind that the users collection doesn’t have to exist for this call to work correctly.  If the collection is not already there, mongodb will happily create the collection for you and then insert the data.

Create the Controller

If you are not familiar with CodeIgniter, the controller classes live under the php/application/controllers directory.  For this example, we are going to create a new controller called MongoTest.php with the following contents:

<?php

class MongoTest extends CI_Controller {

    public function index() {
        $this->load->model('usermodel');
        $result = $this->usermodel->createUser("myuser", "mypassword");

        $this->load->view('mongodbtest_view');
    }

}

?>

The index function is the default function that will get called when a HTTP request is initiated for this URL.  The first thing we do is load the usermodel that we created in the previous step.  This will allow us to call directly into functions that we have specified in that model class.

We then call createUser and pass in a username of myuser and a password of mypassword.  This will in turn call the model creatUser function that we created in the previous step and perform the insert into the database.

The last code snippet tells the framework which view display to the user.  In the case we are going to display a view that we will create in the next step.

Create the view

All view and presentation logic should be located under the mymongoapp/php/application/view directory.  Create a file called mongodbtest_view.php and add the following contents:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Welcome to CodeIgniter running mongodb</title>

    <style type="text/css">

    ::selection{ background-color: #E13300; color: white; }
    ::moz-selection{ background-color: #E13300; color: white; }
    ::webkit-selection{ background-color: #E13300; color: white; }

    body {
        background-color: #fff;
        margin: 40px;
        font: 13px/20px normal Helvetica, Arial, sans-serif;
        color: #4F5155;
    }

    a {
        color: #003399;
        background-color: transparent;
        font-weight: normal;
    }

    h1 {
        color: #444;
        background-color: transparent;
        border-bottom: 1px solid #D0D0D0;
        font-size: 19px;
        font-weight: normal;
        margin: 0 0 14px 0;
        padding: 14px 15px 10px 15px;
    }

    code {
        font-family: Consolas, Monaco, Courier New, Courier, monospace;
        font-size: 12px;
        background-color: #f9f9f9;
        border: 1px solid #D0D0D0;
        color: #002166;
        display: block;
        margin: 14px 0 14px 0;
        padding: 12px 10px 12px 10px;
    }

    #body{
        margin: 0 15px 0 15px;
    }

    p.footer{
        text-align: right;
        font-size: 11px;
        border-top: 1px solid #D0D0D0;
        line-height: 32px;
        padding: 0 10px 0 10px;
        margin: 20px 0 0 0;
    }

    #container{
        margin: 10px;
        border: 1px solid #D0D0D0;
        -webkit-box-shadow: 0 0 8px #D0D0D0;
    }
    </style>
</head>
<body>

<div id="container">
    <h1>Welcome to CodeIgniter with MongoDB running on OpenShift</h1>

    <div id="body">
        <p>Congratulations.  You have CodeIgniter and MongoDB running on OpenShift!</p>
    </div>

    <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>

</body>
</html>

Deploy and test your application

At this point we have created an application, added mongodb hosted at MongoLab, installed CodeIgniter, added the mongodb library to our application, and created a MVC sample application.  Now comes the fun part, testing our changes.  Change directories to the top level of your application, which should be the mymongoapp directory and perform the following commands:

$ git add .
$ git commit -am "Created MVC application"
$ git push

At this point, you should see a congratulations message on the screen.

What's Next?