PHPackages                             mongojacket/mongojacket - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. mongojacket/mongojacket

ActiveLibrary[Database &amp; ORM](/categories/database)

mongojacket/mongojacket
=======================

A wrapper for PHP MongoDB drivers

2161PHP

Since Mar 10Pushed 13y ago1 watchersCompare

[ Source](https://github.com/souravray/mongojacket)[ Packagist](https://packagist.org/packages/mongojacket/mongojacket)[ RSS](/packages/mongojacket-mongojacket/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

MongoJacket
===========

[](#mongojacket)

A simple abstraction layer for [PHP MongoDB Driver](http://www.php.net/manual/en/book.mongo.php)

Build Matrix
------------

[](#build-matrix)

[![Build Status](https://camo.githubusercontent.com/434b0c19c7561aeacb86b266f7b41370595d9117760a27c36f5ccd3868784db9/68747470733a2f2f7472617669732d63692e6f72672f736f757261767261792f6d6f6e676f6a61636b65742e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/souravray/mongojacket)

- Current Build: 0.0.1\_nb
- Stability: Unstable
- Compatibility:
    - MongoDB &gt;= 1.5.x
    - PHP &gt;= 5.4.x

Table of contents
-----------------

[](#table-of-contents)

- [Quick Start](#quick-start)
- [API](#api)
- [Callbacks](#callbacks)
- [Exception Handling](#exception-handling)
- [Binding of Custom Methods](#binding-of-custom-methods)
- [Middleware](#middleware)
- [Validator](#validator)
- [ToDos](#todos)

Quick Start
-----------

[](#quick-start)

MongoJacke is not one of those bloated ODMs you encounter everyday. It essentially gives developers an interface similar to native Mongo driver. In addition to that, MongoJacke allows developer to add custom methods, callbacks and validation rules.

### Installation

[](#installation)

##### Install via Composer

[](#install-via-composer)

Install composer in your project

```
    curl -s https://getcomposer.org/installer | php

```

Create a `composer.json` file in your project

```
    {
        "require": {
            "mongojacket/mongojacket": "dev-master"
        }
    }

```

Run composer install

```
    php composer.phar install

```

Add this line to your application

```
    require 'vendor/autoload.php';
```

##### Manual Installation

[](#manual-installation)

Git clone mongojacket in your project

```
    git clone git://github.com/souravray/mongojacket.git

```

Include following line to your application

```
// inclue MongoJacket file
    include_once("Path To MongoJacket/index.php");
// register autoloader
    spl_autoload_register('MongoJacket\MongoJacketAutoloader');
```

API
---

[](#api)

API is exactly same as PHP-Mongo driver.

### Connect

[](#connect)

Using native driver

```
    $m = new MongoClient("mongodb://user:pas@localhost:27017/test");
```

Using MongoJacket

```
    $jacket =  new MongoJacket\Jacket('localhost:27017', 'test', 'user', 'pass');
```

### Database

[](#database)

Using native driver

```
    $db = $m->selectDB("rockband");
```

Using MongoJacket

```
    $db =  $jacket->db('rockband');
```

### Collection

[](#collection)

Using native driver

```
    $collection = $db->selectCollection('bands');
```

Using MongoJacket

```
    $collection =  $db->collection('bands');
```

### Command Chaining

[](#command-chaining)

You can call commands in chain

```
    $jacket->db('rockband')->collection('bands')->find();
```

### Queries

[](#queries)

Currently only following query methods of native PHP-Mongo drive are supported in MongoJacket.

`find`, `findOne`, `insert`, `save`, `batchInsert`, `findAndModify`, `Update`

MongoJackect query methods return the same value as native APIs or an exception object in case of any exception.

##### [Back to Index](#table-of-contents)

[](#back-to-index)

Callbacks
---------

[](#callbacks)

As an additional parameter to any query method you can pass an anonymous function as callback. All the following syntax are correct. Callback method can return a value to the caller of the parent query.

```
// pass a callback method to find method
// without any criteria or field specified
    $bands = $jacket->db('rockband')->collection('bands')->find(
                function($results,$error){
                    // data transformation logic
                    return $results; //return to the calling parameter
                }
            );

// pass a callback method to find method
// with only criteria specified
    $bands = $jacket->db('rockband')->collection('bands')->find(
                array("year" => array('gr' => 1963)) ,
                function($results,$error){
                    // data transformation logic
                    return $results; //return to the calling parameter
                }
            );

// pass a callback method to find method
// with only criteria and field specified
    $bands = $jacket->db('rockband')->collection('bands')->find(
                array("year" => array('gr' => 1963)) ,
                array("name", "album", "awards", "members") ,
                function($results,$error){
                    // data transformation logic
                    return $results; //return to the calling parameter
                }
            );
```

### Using $this and Infinite Command Sequencing

[](#using-this-and-infinite-command-sequencing)

In the callback method you are allowed tho use `$this`. It is allowed to call another query method and pass a callback function inside a callback function. Theoretically it can be looped till infinite time. All inner queries and callbacks will be executed in sequence.

```
// command/ callback sequencing
    $bands = $jacket->db('rockband')->collection('bands')->find(
                function($results,$error){
                    // check some condition
                        // add a new entry
                        $this->save( array(
                                            "name"=>"Velvet Revolver",
                                            "members"=> array("Scott Weiland",
                                                                "Slash",
                                                                "Dave Kushner",
                                                                "Matt Sorum",
                                                                "Duff McKagan"),
                                            "year"=>1984) ,
                                    function ($result, $error){
                                        // some code here
                                    } );
                    return $results; //return to the calling parameter
                }
            );
```

##### [Back to Index](#table-of-contents)

[](#back-to-index-1)

Exception Handling
------------------

[](#exception-handling)

MongoJacket exceptions are objects `\MongoJacket\Exception`. Exceptions are not thrown in MongoJacket APIs. In case of an exception MongoJacket will return an `\MongoJacket\Exception` object instead of result when callback method is not available. You can validate the response like bellow.

```
// no callback is added
    $isinseted = $jacket->db('rockband')->collection('bands')->save( array(
                                                    "name"=>"Velvet Revolver",
                                                    "members"=> array("Scott Weiland",
                                                                        "Slash",
                                                                        "Dave Kushner",
                                                                        "Matt Sorum",
                                                                        "Duff McKagan"),
                                                    "year"=>1984) );
    if(is_a($isinseted, '\MongoJacket\Exception' ){
        // some diagnostic action
    }
```

when a callback function is added. Exception object is passed as the second parameter to the function. If no exception is there then `null` is passed in that place.

```
// a callback is added
    $bands = $jacket->db('rockband')->collection('bands')->find(
                function($results,$error){
                    if(is_null($error)
                        && is_a($error, '\MongoJacket\Exception' ){
                        // some diagnostic action
                    }
                }
            );
```

##### [Back to Index](#table-of-contents)

[](#back-to-index-2)

Binding of Custom Methods
-------------------------

[](#binding-of-custom-methods)

A custom method can be binded to a collection like bellow.

```
    $jacket->db('rockband')->collection('bands')->bind(
                                                    "McKaganBands",
                                                    function (){
                                                       return $this->find(array("member" => 'Duff McKagan'));
                                                    });
```

Calling custom method

```
    $jacket->db('rockband')->collection('bands')->McKaganBands();
```

### Passing Parameters to Binded Methods

[](#passing-parameters-to-binded-methods)

The function cannot accept multiple parameters in the definition. Any parameter passed during custom method call can be accessed using `func_get_args()`.

##### [Back to Index](#table-of-contents)

[](#back-to-index-3)

Middleware
----------

[](#middleware)

MongoJacket support a mechanism for adding middleware. A simple middleware can be written like bellow.

```
    class MyMiddleware extends \MongoJacket\Middleware{
        // your middileware logic should be here
        public function call(){
            // here do some magic
            $this->next->call();
        }
    }
```

Middleware can be bind to following `Pre` or `Post` events: `init`, `find`, `save`, `delete`At present only Collection implements middleware protocol, and the registry method is a private method. MongoJacket will add ability to register third-party middlewars in future.

##### [Back to Index](#table-of-contents))

[](#back-to-index-4)

Validator
---------

[](#validator)

MongoJacket `validator` is a Middleware. MongoJacket does not required any schema definition for mapping. It allows to add validation rules to Document elements for a collection. The validator method get called during `Pre Save` event. If a validation fails then an the query fails and exception object is returned.

```
// Validator-1
    $jacket->db('rockband')->
    collection('bands')->
    validator('year',
                function ($var) {
                    // no new band after 2010 is allowed
                    return ($vardb('rockband')->
    collection('bands')->
    validator('name',
                function ($var) {
                    //  Limp Bizkit is not allowed
                    return !($var=="Limp Bizkit");
                }
            );

// this will fail due to Validator 1
    $jacket->db('rockband')
    ->collection('bands')->insert(array(
            "name"=>"Modern Alarms",
            "members"=> array(  "Dominic Barber",
                                "David Fraser",
                                "Colm Feeley",
                                "Andy Gledhill"),
            "year"=>2012)
    );

// this will fail due to Validator 2
    $jacket->db('rockband')
    ->collection('bands')->insert(array(
            "name"=>"Limp Bizkit",
            "members"=> array(  "Fred Durst",
                                "Wes Borland",
                                "Sam Rivers",
                                "John Otto",
                                "DJ Lethal"),
            "year"=>1994)
    );
```

### Overriding Validor and Sequencing

[](#overriding-validor-and-sequencing)

By default if another validator is added to same entity, then the first validation rule will be over ridden by the lastly added rule.

```
// Validator-1
    $jacket->db('rockband')->
    collection('bands')->
    validator('year',
                function ($var) {
                    // only bands formed before 2012 are allowed
                    return ($vardb('rockband')->
    collection('bands')->
    validator('year',
                function ($var) {
                    // only bands formed after 1994 is allowed
                    return ($var>1994);
                }
            );

    // this will be success because the final rule: year > 1994
    $jacket->db('rockband')
    ->collection('bands')->insert(array(
            "name"=>"Modern Alarms",
            "members"=> array(  "Dominic Barber",
                                "David Fraser",
                                "Colm Feeley",
                                "Andy Gledhill"),
            "year"=>2012)
    );

    // this will fail because the final rule: year > 1994
    $jacket->db('rockband')
    ->collection('bands')->insert(array(
            "name"=>"Limp Bizkit",
            "members"=> array(  "Fred Durst",
                                "Wes Borland",
                                "Sam Rivers",
                                "John Otto",
                                "DJ Lethal"),
            "year"=>1994)
    );
```

In the above example if the second validator Boolean `false` is passed as second parameter to the `validator` method, then both the validation rules will be chained.

```
// Validator-1
    $jacket->db('rockband')->
    collection('bands')->
    validator('year',
                function ($var) {
                    // only bands formed before 2012 are allowed
                    return ($vardb('rockband')->
    collection('bands')->
    validator('year',
                function ($var) {
                    // only bands formed after 1994 is allowed
                    return ($var>1994);
                },
                false
            );

    // this will fail because the final rule: 1994 < year < 2012
    $jacket->db('rockband')
    ->collection('bands')->insert(array(
            "name"=>"Modern Alarms",
            "members"=> array(  "Dominic Barber",
                                "David Fraser",
                                "Colm Feeley",
                                "Andy Gledhill"),
            "year"=>2012)
    );

    // this will fail because the final rule: 1994 < year < 2012
    $jacket->db('rockband')
    ->collection('bands')->insert(array(
            "name"=>"Limp Bizkit",
            "members"=> array(  "Fred Durst",
                                "Wes Borland",
                                "Sam Rivers",
                                "John Otto",
                                "DJ Lethal"),
            "year"=>1994)
    );
```

##### [Back to Index](#table-of-contents)

[](#back-to-index-5)

ToDos
-----

[](#todos)

##### [Back to Index](#table-of-contents)

[](#back-to-index-6)

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/9dc4b1529dbe2ef00d94857761f1f22c732cd95e6848549fbb8fd09fdd195ae3?d=identicon)[souravray](/maintainers/souravray)

---

Top Contributors

[![souravray](https://avatars.githubusercontent.com/u/364657?v=4)](https://github.com/souravray "souravray (60 commits)")

### Embed Badge

![Health badge](/badges/mongojacket-mongojacket/health.svg)

```
[![Health](https://phpackages.com/badges/mongojacket-mongojacket/health.svg)](https://phpackages.com/packages/mongojacket-mongojacket)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
