How to deploy a PHP Application using MongoDB on Windows Azure

Author: Nick Ghinazzi <a-nickgh@microsoft.com>

Date: Tuesday, July 3, 2012, 12:14:28 PM

Tags: Scenario, MongoDB, PHP

Table of Contents

Overview

This tutorial shows you how to create a PHP application using a MongoDB replica set. At the end of this tutorial you will have a basic application that reads data from the replica set and allows users to add data to the database.

Prerequisites

Windows Azure account
Administrator rights on your local machine

Create a MongoDB replica set

MongoDB is a high-performance open source database that features document-oriented storage with data integrity guaranteed through journaling and replication. To create a MongoDB replica set in Windows Azure follow this tutorial.

Install MongoDB package on your local machine

Before you can write your PHP code to connect to your MongoDB replica set you will need to download the MongoDB PHP extension and install it. The following link leads to a page that has instructions and file downloads links for your installation: http://www.php.net/manual/en/mongo.installation.php. You can use phpInfo() to determine which version you need to download if you are unsure. Essentially you will be placing a php_mongo.dll in your \PHP\ext folder and updating the php.ini file to install that extension.

PHP-MongoDB-FileSystem

If you are using Microsoft WebMatrix or another local development environment that utilizes Internet Information Services (IIS) Express, a feature of Windows Server, the php.ini file is located at C:\Program Files (x86)\IIS Express\PHP\v5.3\php.ini, and you will need to add the following.

extension=php_mongo.dll

After you complete these step, restart IIS. In Microsoft WebMatrix, you can restart IIS Express from the ribbon.

PHP-MongoDB-IISReset

Create your MongoDB application in PHP

Now you can write your PHP application to connect to your MongoDB replica set and create your application. The sample application code can be found at the bottom of this tutorial, though there are a couple things to note.

Connect to the MongoDB replica set

The following line of code connects your application to the MongoDB replica set. Theis the name given to your replica set during creation. By default this name is "rs" but can be anything you choose. Theis the URI to your MongoDB replica set.

 $mongo = new Mongo(<dns-name>, array("replicaSet" => <replica-set-name>));

Create the database and collection It is very easy to create databases and collections (which are analogous to SQL tables) in MongoDB. This line demonstrates how to create a database.

$db = $mongo->testdb;

This line assigns the $db variable to testdb. If testdb does not already exist, a database is created with that name.

Creating the collection is similar. When the following code is run it creates the collection only if it doesn't already exist.

$collection = new MongoCollection($db, 'songs');

The code produces the following application.

PHP-MongoDB-Application

Preview and publish your PHP application to Windows Azure

To publish your PHP application using MongoDB to Windows Azure you need to use Windows Azure web roles to deploy your application. You will need to get the cdmlets, create a web role package and deploy it.

Get the Windows Azure PowerShell cmdlets

The easiest way to get the Windows Azure PowerShell cmdlets is to install the Windows Azure SDK for PHP: download the Windows Azure SDK for PHP. That link downloads the Web Platform Installer and sets you up to install both the Windows Azure PowerShell cmdlets and the Windows Azure Windows Azure emulation environment," which includes the storage and compute emulators, according to WinEdit.

After you install the cmdlets, follow these steps to import your publish settings. You only need to perform these steps once.

  1. Start Windows Azure PowerShell as an administrator (from the Start menu, find Windows Azure PowerShell, right-click it, and then click Run as Administrator).
  2. Download your publish settings by executing the following command.
    Get-AzurePublishSettingsFile
    
  3. In your web browser, sign in with your Windows Azure account credentials. (Make note of where you save the .publishsettings file.)
  4. Import your publish settings with this command.
    Import-PublishSettingsFile <path to downloaded .publishsettings file>
    

Create a PHP web role

After you import your publish settings, create a PHP web role by following these steps:

  1. Create a new Windows Azure project. Note that this command creates a new directory called myAzureProject and automatically changes directories to it. You can change the name of the new directory.
    New-AzureServiceProject myMongoPHPProject
    
  2. From the new directory (myAzureProject by default), add a PHP web role.
    Add-AzurePHPWebRole myWebRole
    

You now have a basic PHP/Windows Azure project. Inspecting the directory structure, you should see something similar to this:

/myAzureProject
    deploymentSettings.json
    ServiceConfiguration.Cloud.cscfg
    ServiceConfiguration.Local.cscfg
    ServiceDefinition.csdef
        /myWebRole
            index.php
            Web.cloud.config
            Web.config
            /bin
                Microsoft.Web.Deployment.dll
                Microsoft.Web.PlatformInstaller.dll
                Microsoft.Web.PlatformInstaller.UI.dll
                setup.cmd
                setup.ps1
                setup_web.cmd
                WebpiCmdLine.exe

You can now replace the code in the index.php file with your application code in the myWebRole folder.

The Add-AzurePHPWebRole cmdlet creates a scaffold project that, when deployed, installs the latest version of PHP available via the Web Platform Installer. This scaffold project is the standard out-of the-box configuration. However, you can customize this configuration by doing the following:

  1. Add a php folder to the bin directory.
  2. Add an ext folder to the php directory, and then put any PHP extensions you want to be available in the folder ( php_mongo.dll for this example).
  3. Add a custom php.ini file to the php directory. You can turn settings on and off, and you can enable extensions as you would with any other PHP installation via this .ini file.
  4. Add extension=php_mongo.dll to the php.ini file.

Publish to Windows Azure

Finally, you can publish your project to Windows Azure with the following command.

Publish-AzureServiceProject

This command attempts to create a cloud service using your project name (myAzureProject in these examples). If that name is not available, you may get an error. If that happens you can deploy it with a different name by using the -ServiceName flag.

Publish-AzureServiceProject -ServiceName myNewServiceName

You can check to see whether a name is available with this command.

Test-AzureName -Service "myAzureProject"

For more information about deploying PHP applications using Windows Azure web roles, including how to test locally using the emulator and enabling RDP access, see Brian Swan's excellent article here.

After you deploy a project, you may need to wait several minutes while Windows Azure provisions and configures new virtual machines for each deployment.

Code

<?php
 // The connection string for the MongoDB replica set. This should be the dns you set up with the replica set.
 $host = "<dns-name>.cloudapp-preview.net";

 // Connect to the MongoDB replica set. Note: "rs" is the default name for the MongoDB replica set if you used the installer.
 $mongo = new Mongo($host, array("replicaSet" => "rs"));
 
 // This enables you to read from a slave if, for some reason, the application cannot reach the master.
 // $mongo->setSlaveOkay(true);
 
    $db = $mongo->testdb;
    $collection = new MongoCollection($db, 'songs');
    
    //Seed the database with initial values. Note: using custom '_id' values ensures that  documents get input only once.
    $a = array("_id" => "9th_Symphony", "title" => "9th_Symphony ", "artist" => "Bethoven", "album" => "Bethoven");
    $collection->insert($a);
    $a = array("_id" => "Nocturne_in_B-flat_minor ", "title" => "Nocturne in B-flat minor ", "artist" => "Frédéric Chopin ", "album" => "Op. 9 No. 1");
    $collection->insert($a);
    $cursor = $collection->find();
 
    // If you have post data, add the new song to the database.
     if ($_POST){
        $sName = $_POST['title'];
        $sArtist = $_POST['artist'];
        $sAlbum = $_POST['album'];
        $sID = str_replace(" ", "_", $sName); //For this example, use the title as ID (converting spaces to '_')
 
        $sSend = array('_id' => $sID, 'title' => $sName, 'artist' => $sArtist, 'album' => $sAlbum, );
        $collection->insert($sSend);
     }
     
 
?>
 
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>OSS on Windows Azure - MongoDB replica set with PHP</title>
    </head>
    <body>
    <div width="100%" align="center">
    <h1>MongoDB-On-Windows-Azure Music List</h1>    
    <p>Song list:</p>
    <table cellpadding=4 cellspacing=0 border="1" bordercolor="black">
        <tr>
            <td>Title</td><td>Artist</td><td>Album</td>
        </tr>
        <?php 
            //Complete the table with the database contents
            foreach ($cursor as $resp) {
                echo "<tr><td>" . $resp["title"] . "</td><td>" . $resp["artist"] . "</td><td>" . $resp["album"] . "</td></tr>";
            }
            //Drop the database table. Here for testing purposes.
            //$response = $db->drop();
 
        ?> 
    </table>
    <p><hr width=70%></p>
    <p>Enter new song:</p>
        <form name="add" method="post" action="<?php echo $PHP_SELF;?>">
        <table cellpadding=4 cellspacing=0 border="1" bordercolor=black>
            <tr><td>Enter a song title: </td><td><input type="text" name="title" /></td></tr>
            <tr><td>Enter the artist: </td><td><input type="text" name="artist" /></td></tr>
            <tr><td>Enter the album: </td><td><input type="text" name="album" /></td></tr>
            <tr><td> ;</td><td><input type="submit" value="Add Song" /></td></tr>
        </table>
        </form>
    </div>
    </body>
</html>
 
blog comments powered by Disqus

Related Content

No related content was found