Building a mobile app backend using MongoDB and Slim – a PHP REST framework

I’ve been toying around in my spare time with HTML5 and building a geographically enabled web app  (possibly making it into a full blown mobile app down the track using PhoneGap or Appcelerator). Anyway, I started off with the back end.

I chose MongoDB as the data store (a nosql database with really simple out of the box geographic indexing). There are a few threads about mongo’s geohashing algorithms not coping at very fine scales, but for my purposes it has all the accuracy I need and the geohashing mechanism is really fast.

I needed a REST interface that my mobile app could use to retrieve nearest locations and to add new locations – both fairly simple requirements as the bulk of the computational work is elegantly handled by the backend database. All I needed was something to build the routes and add in my own validation – this is where Slim comes in.

Slim is a micro framework to build REST services and it does this one thing very well. It allows me to build routes for GET POST PUT and DELETE requests and hand them off to appropriate functions in my data model.  minimal example:


           require 'Slim/Slim.php';
           require 'models/LocationStore.php';

           $app = new Slim();
           $ls  = new LocationStore();

           $app->get('/near/:lat,:lon', function ($lat, $lon) {
                header("Content-Type: application/json");
                echo json_encode($ls->getNear($lat, $lon));



So a GET request to http://myserver/near/-37.8,143.2 would be routed to a function that queries my database for locations near the latitude and longitude passed in. I can also use some neat features built in to Slim to validate the passed in values against a regular expression.

There is more to it of course and a number of templating tools can be plugged in to make it into a more fully featured web framework.

Next up is the front end HTML5 code, but that’s a subject for another post.

Slim framework website:









5 responses to “Building a mobile app backend using MongoDB and Slim – a PHP REST framework”

  1. rakri avatar

    Hi ,
    interesting subject …
    Can You show your example , please ?
    I’m trying to develop an application based on geolocation too…

  2. Akash Patel avatar
    Akash Patel

    Can you describe on how to integrate mongoDB into Slim?

    1. peter avatar

      I built a class that uses the PHP mongo functions:


      class Places{

      private $connection;
      private $db;
      private $collection;
      function __construct($conf) {
      $this->connection = new Mongo( $conf['mongo_host'].":".$conf['mongo_port'],
      array("user" => $conf['mongo_user'], "password" => $conf['mongo_pass'])

      $this->db = $this->connection->selectDB($conf['mongo_db']);
      $this->collection = $this->db->places;

      function getNear($lat, $long){
      $lt = floatval($lat);
      $lg = floatval($long);
      $res = $this->db->command(array("geoNear" => "places", "near" => array(floatval($lt),floatval($lg)), "distanceMultiplier" => (6371 * M_PI / 180.0)));
      return $res;

      function addPlace($place){
      $item = array("name" => $place['name'],
      "address" => $place['address'],
      "position" => array("lat" => floatval($place['lat']), "long" => floatval($place['long'])),
      "notes" => $place['notes'],
      "device" => $place['device']);

      return $this->collection->insert($item, true);


      Then included this file in the index.php file and used it in routes.

      e.g. to get Places near the current location:

      //GET route
      Slim::get('/near_mobile/:lat,:long', function ($lat, $long) {
      global $places;
      $result = $places->getNear($lat, $long);
      print "<body> <ul data-role='listview' data-theme='g'>";
      foreach($result as $r){
      print "<li>";
      print "<a href='' rel="nofollow">";
      print $r['address'];
      print "</a>";
      print "</li>";

      print "</ul>";
      print "</body>";

      })->conditions(array('lat' => '([-d.]{1,10})',
      'long' => '([-d.]{1,10})'));

  3. Sonus avatar

    Really Great Post .

    Definitely gonna try this

  4. varalakshmi avatar

    Hello sir,
    i am new to mongodb and slim framework, the above snippet make me difficult to understand, actually i just inserted my data into mongodb. now i am trying to check with different tutorials and code snippets to make it rest api’s of my mongodb data. Can you pls help me out.

Leave a Reply

Your email address will not be published. Required fields are marked *