Book Image

PHP and MongoDB Web Development Beginner's Guide

Book Image

PHP and MongoDB Web Development Beginner's Guide

Overview of this book

With the rise of Web 2.0, the need for a highly scalable database, capable of storing diverse user-generated content is increasing. MongoDB, an open-source, non-relational database has stepped up to meet this demand and is being used in some of the most popular websites in the world. MongoDB is one of the NoSQL databases which is gaining popularity for developing PHP Web 2.0 applications.PHP and MongoDB Web Development Beginner’s Guide is a fast-paced, hands-on guide to get started with web application development using PHP and MongoDB. The book follows a “Code first, explain later” approach, using practical examples in PHP to demonstrate unique features of MongoDB. It does not overwhelm you with information (or starve you of it), but gives you enough to get a solid practical grasp on the concepts.The book starts by introducing the underlying concepts of MongoDB. Each chapter contains practical examples in PHP that teache specific features of the database.The book teaches you to build a blogging application, handle user sessions and authentication, and perform aggregation with MapReduce. You will learn unique MongoDB features and solve interesting problems like real-time analytics, location-aware web apps etc. You will be guided to use MongoDB alongside MySQL to build a diverse data back-end. With its concise coverage of concepts and numerous practical examples, PHP and MongoDB Web Development Beginner’s Guide is the right choice for the PHP developer to get started with learning MongoDB.
Table of Contents (17 chapters)
PHP and MongoDB Web Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface

Time for action - creating a connection to the MongoDB server from PHP


  1. 1. Open up your text editor and add the following code in a new file:

    <?php
    try{
    $mongo = new Mongo(); //create a connection to MongoDB
    $databases = $mongo->listDBs(); //List all databases
    echo '<pre>';
    print_r($databases);
    $mongo->close();
    } catch(MongoConnectionException $e) {
    //handle connection error
    die($e->getMessage());
    }
    
  2. 2. Save the file as test_connection.php under the DocumentRoot of your web server.

  3. 3. Open up your browser, and execute the script by going to the location http://localhost/test_connection.php:

What just happened?

We just wrote a simple PHP program to test if the PHP-MongoDB driver we installed works correctly. The program does two simple things. First, it creates a connection to the Mongo server, then it lists all the databases in the server.

Let's examine the code. We created a connection from PHP to MongoDB by instantiating a Mongo object:

try{
$mongo = new Mongo();
……………………………………………………
} catch(MongoConnectionException $e) {
die($e->getMessage());
}

We instantiated the object within a try/catch block to handle the exception named MongoConnectionException in case PHP fails to connect. Once the connection was made, we invoked the listDBs() method on the Mongo object. It returned an associative array, containing three fields. The first field—databases—is an array of associative arrays, each one corresponding to a database in the server, giving us the name of the database, its size in bytes, and a flag specifying if the database is empty or not.

Array
(
[databases] => Array
(
[0] => Array
(
[name] => myfirstdb
[sizeOnDisk] => 67108864
[empty] =>
)
[1] => Array
(
[name] => adming
[sizeOnDisk] => 1
[empty] => 1
)
)
[totalSize] => 67108864
[ok] => 1
)

The totalSize field corresponds to the total size of data in the server (in bytes) and the ok flag specifies if the method ran successfully. Finally, we closed the connection by invoking the close() method on the Mongo object.

Configuring the PHP-MongoDB connection

When no parameter is passed to the constructor of the Mongo class, it connects to the Mongo server running on localhost, on port 27107 (or whatever value is specified for mongo.default_host and mongo.default_port in php.ini). If we want to connect to a server running on a different host and/or port, we can pass the connection string (mongodb://<hostname>:<port_number>) as the $server parameter to the Mongo constructor. For example, to connect to a Mongo server listening on port 8888, we will type the following command:

$mongo = new Mongo($server="mongodb://localhost:8888");

Specifying timeout for the connection attempt

We can specify for how long (in milliseconds) the driver should attempt to connect to the MongoDB server:

try {
$mongo = new Mongo($options=array('timeout'=> 100))
} catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}

We supplied an array {'timeout' => 100} as the $option argument to the Mongo constructor. In case PHP fails to connect within 100 milliseconds, it will throw an exception named MongoConnectionException.

Have a go hero connect to a MongoDB server on a networked computer

Suppose your computer is connected to a local area network. There is another computer in the network, running on the IP address 192.168.1.101. It is hosting a MongoDB server that is listening on port 8000. Write a PHP script that connects to that MongoDB server, in under one second, and lists all the databases hosted there.