MongoDB Codeigniter integration using official PHP drivers

Since Codeigniter does not officially support MongoDB at this time, MongoDB Codeigniter integration is not very easy currently. So, in this tutorial I will explain how we can install MongoDB with Codeigniter using official PHP drivers provided by MongoDB. Let’s get started :

Prerequisites :

  1. A VPS(Virtual Private Server) with a web server (e.g. Apache, NGINX), PHP and MongoDB server installed. If you have a shared hosting account, check with your service provider if they have MongoDB installed.
  2.  Codeginiter framework installed.
  3. Composer in your development environment.

Install the mongodb extension

The MongoDB PHP Library is a high-level abstraction for the MongoDB PHP driver. So, we need to install the mongodb extension before we can use the MongoDB PHP Library for MongoDB codeigniter integration. Follow below steps:

PECL maintains mongodb extension for PHP, so we’ll install it from there.

sudo pecl install mongodb

Now, add extension=mongodb.so to the php.ini file like below

sudo echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`

Depending upon your PHP version, location of php.ini file may be different in case you are planning to edit it manually.

Install the PHP MongoDB Library

Change your current directory to the root of your Codeignier installation. This is usually where the index.php file is located. Now run the below command:

sudo composer require mongodb/mongodb

You will see something like below confirming libraries and other dependencies were installed:

./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing mongodb/mongodb (1.0.0)
    Downloading: 100%         

Writing lock file
Generating autoload files

Codeigniter 3 ships with its own composer.json file, which you can modify as below and add the mongodb dependency:

"require": {
"php": ">=5.2.4",
"mongodb/mongodb": "^1.0.0"
}

Now run the composer update command:

php composer.phar update

Once either of the above steps is completed successfully, go to vendor directory and verify that mongodb directory is present there. If its there, proceed with next steps.

Create MongoDB configuration file

Now, create a file config_mongo.php in the codeigniter’s config directory and paste below contents in it. Replace the values as per your details:

config_mongo.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$config['mongodb']['host'] = 'localhost'; // your host url or ip address
$config['mongodb']['port'] = 27017; // MongoDB port. You can leave it blank for default port
$config['mongodb']['db'] = 'mdb1'; // The Database you want to connect to
//username for the DB authentication. Make sure DB user with sufficient authorization has been created. 
//Read https://docs.mongodb.com/manual/reference/command/createUser/#dbcmd.createUser
$config['mongodb']['username'] = 'test3'; 
$config['mongodb']['password'] = 'password'; //password for the above user
$config['mongodb']['collection'] = 'mdbc1'; // collection you want to connect to. 

Create Codeigniter Library for MongoDB

Now, we will create a custom Codeigniter library to connect the MongoDB drivers with our CI framework.

Create a file Mongodb.php in the libraries directory of Codeigniter installation and paste below content in it.

libraries/Mongodb.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Mongodb {
    protected $CI;

        // We'll use a constructor, as you can't directly call a function
        // from a property definition.
        public function __construct($param=[])
        {
                // Assign the CodeIgniter super-object
                $this->CI = &get_instance();
                
                // if the values from param exist, then assign them to variables for later usage
                $this->p_host = isset($param['host']) ? $param['host'] : \NULL;
                $this->p_port = isset($param['port']) ? $param['port'] : \NULL;
                $this->p_db = isset($param['db']) ? $param['db'] : \NULL;
                $this->p_collection = isset($param['collection']) ? $param['collection'] : \NULL;
                
                //test the values from param by using the echo statement below, if needed
                //echo "$p_host,$p_port, $p_db, $p_collection <br>" ;
 
        }
        public function connection() {
            // load the config file config_mongo
                $this->CI->config->load('config_mongo', TRUE);
            //Check param values. If param values are present, ignore the config file values for connection paramenters   
                $host = is_null($this->p_host) ? $this->CI->config->item('host','mongodb','config_mongo') : $this->p_host;
                $port = is_null($this->p_port) ? $this->CI->config->item('port','mongodb','config_mongo') : $this->p_port ;
                $db = is_null($this->p_db) ? $this->CI->config->item('db','mongodb','config_mongo') : $this->p_db ;
                $coll = is_null($this->p_collection) ? $this->CI->config->item('collection','mongodb','config_mongo') : $this->p_collection ;
            // username and password for connection being loaded from config file only for security reasons
                $username = $this->CI->config->item('username','mongodb','config_mongo') ;
                $password = $this->CI->config->item('password','mongodb','config_mongo') ;
                
                //verify the final values by using the echo statemet below if needed
                //echo "$host,$port, $db, $coll,$username,$password <br>" ;
                
                // $mongo['connection'] is the connection URI as per mongodb 
                // docs: https://docs.mongodb.com/manual/reference/connection-string/
                // This statement will establish actual connection to your mongodb using all the parameters provided.
                $mongo['connection'] = new MongoDB\Client("mongodb://$username:$password@$host:$port/$db");
                
                //If you are just testing MongoDB and do not have authentication enabled, you can remove 
                // username and password parameters. In that case, you can use below statement for connection
                // ,comment the above one and also remove username and password from config file.
                
                //$mongo['connection'] = new MongoDB\Client("mongodb://$host:$port");
                
                // Getting the collection using the param or config values. This can be overridden by directly
                // using the above connection directly from application code.
                $mongo['collection'] = $mongo['connection']->$db->$coll ; 
                
                //Return the CONNECTION and COLLECTION values back
                return $mongo ;
        }
}

Explanation of above code:

The above library can be loaded with additional parameters from the application code. This gives us flexibility to load the library from application at run time and override the configuration from config file.

Additionally, if you are not using authentication, you can use

$mongo['connection'] = new MongoDB\Client("mongodb://$host:$port");

for connection instead of the statement mentioned in the above code. But make sure you use proper authentication in production or with publicly accessible installation.

Create a controller method to verify the installation

Now, create a file Mongo_test.php in the controller directory and paste below code in it. We will insert some test values and verify that installation is working as expected:

controllers/Mongo_test.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Mongo_test extends CI_Controller{
    //put your code here
    public function index() {
        $mongo_parms = ['host' => "localhost",
            'port' => 27017,
            'db' => "mdb2",
            'collection' => "mdb2c"];
        $this->load->library('mongodb',$mongo_parms);
        // If you do not want to pass the parameters at run time and use the ones from config file, you can use below 
        // statement instead. Comment the above one and do  not define the param values.
        // $this->load->library('mongodb');
        
        //Below are some test values to insert and verify the installation
        $biz[] = ['name' => 'biz name',
            'address' => 'test address'] ;
        
        //Access the collection from the library 
        $collection = $this->mongodb->connection()['collection'];
        
        // If you want to modify any of the connection parameters, you can directly access the connection using 
        // below $connection statement.
        $connection = $this->mongodb->connection()['connection'];
        //var_dump($connection);
        
        //Insert the above values to the collection
        $insert = $collection->insertOne($biz) ;
        
        // Retrieve the values from collection
        $result = $collection->find();
        foreach ($result as $k=>$v) {
            var_dump($v) ;
        }
        
    }
}

If you want to use the config file parameters, then you can skip loading the mongodb library with additional parameters, as explained in the code.

Now, access mongo_test from your web application e.g. if you have CI installed on your localhost, then go to http://localhost/index.php/mongo_test . If everything is setup correctly, you should see the values from test array we just inserted.

If there is any issue, just make sure all steps are followed correctly. If there is till any problem, let me know the details using the comments.

Important notes on MongoDB Codeigniter tutorial:

  1. The drivers are provided by MongoDB, so you will have to use methods provided in the mongodb php documentation.
  2. You will not be able to use native codeignier database mathods for database manipulation needs.

Other questions this post would be able to help with

  1. How to install MongoDB with codeigniter.
  2. Codeigniter MongoDB tutorial.

References:

  1. php.net
  2. MongoDB documentation

Leave a Reply

Technology Central © 2014 - 2017 | Privacy Policy | Website Terms & Conditions