PHPackages                             lewestopher/cakephp-monga - 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. [Framework](/categories/framework)
4. /
5. lewestopher/cakephp-monga

ActiveCakephp-plugin[Framework](/categories/framework)

lewestopher/cakephp-monga
=========================

CakeMonga plugin for CakePHP

0.5.0(9y ago)161.8k3[5 issues](https://github.com/LeWestopher/cakephp-monga/issues)1MITPHPPHP &gt;=5.4.16

Since Aug 12Pushed 8y ago3 watchersCompare

[ Source](https://github.com/LeWestopher/cakephp-monga)[ Packagist](https://packagist.org/packages/lewestopher/cakephp-monga)[ RSS](/packages/lewestopher-cakephp-monga/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (5)Versions (17)Used By (1)

cakephp-monga
=============

[](#cakephp-monga)

[![Framework](https://camo.githubusercontent.com/580b6b7df52e2ed143640131d9feacd08c3f33d34c98442752cc5551a47ef2af/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4672616d65776f726b2d43616b65504850253230332e782d6f72616e67652e737667)](http://cakephp.org)[![Database](https://camo.githubusercontent.com/259ca177f83bae5dfba19533ddc6f534db12f874b21c2f45d748e438a85cb5ec/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f44617461626173652d4d6f6e676f44422d677265656e2e737667)](https://www.mongodb.com)[![license](https://camo.githubusercontent.com/91a982d5397ab27caf75725105e5b2483d9442313c086e40b31dedbf80581752/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f4c65576573746f706865722f63616b657068702d6d6f6e67612e7376673f6d61784167653d32353932303030)](https://github.com/LeWestopher/cakephp-monga/blob/master/LICENSE)[![Github All Releases](https://camo.githubusercontent.com/0b8df0dbe7b8d745190aa8338af823227909a046832ab510d5c9780cf9f2d54c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6c65776573746f706865722f63616b657068702d6d6f6e67612e7376673f6d61784167653d32353932303030)](https://packagist.org/packages/lewestopher/cakephp-monga)[![Travis](https://camo.githubusercontent.com/04cc111471953ede3d94491d428aab774e68b8ff59cbfd12f0d80e80e1d325d5/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f4c65576573746f706865722f63616b657068702d6d6f6e67612e7376673f6d61784167653d32353932303030)](https://travis-ci.org/LeWestopher/cakephp-monga)[![Coverage Status](https://camo.githubusercontent.com/a3ff7e03d94f071546b2e505a2c77f24a627075eebccffb91f9c19f0b8e01648/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f4c65576573746f706865722f63616b657068702d6d6f6e67612f62616467652e737667)](https://coveralls.io/github/LeWestopher/cakephp-monga)

A plugin for accessing MongoDB NoSQL data stores in CakePHP 3.x.

### Requirements

[](#requirements)

- Composer
- CakePHP 3.x
- PHP 5.4+
- MongoDB
- Pecl Mongo extension

### Installation

[](#installation)

In your CakePHP root directory: run the following command:

```
composer require lewestopher/cakephp-monga

```

Then in your config/bootstrap.php in your project root, add the following snippet:

```
// In project_root/config/bootstrap.php:

Plugin::load('CakeMonga');
```

or you can use the following shell command to enable to plugin in your bootstrap.php automatically:

```
bin/cake plugin load CakeMonga

```

### Extended Documentation

[](#extended-documentation)

For the extended docs, please visit our [Wiki](https://github.com/LeWestopher/cakephp-monga/wiki).

### Usage

[](#usage)

First, we define a new Datasource in our config/app.php file with our namespaced Connection class name:

```
// In project_root/config/app.php:

'Datasources' => [

    'default' => [
        // ... Default SQL Datasource
    ],

    'mongo_db' => [
        'className' => 'CakeMonga\Database\MongoConnection',
    ]
],
```

Then we can instantiate our MongoDB connection anywhere that we need in the application via the ConnectionManager class:

```
class ExampleController extends Controller
{
    public function index()
    {
        $cake_monga = ConnectionManager::get('mongo_db');
    }
}
```

Then from there we can get our Monga instance by using the `connect()` method on the returned connection:

```
$cake_monga = ConnectionManager::get('mongo_db');
$mongodb = $cake_monga->connect(); // An instance of the Monga Connection object
$database_list = $mongodb->listDatabases(); // We can call all of the methods on that Monga object provided by their API
```

Note that the $mongodb object instantiated above with the `connect()` method is the same object returned by Monga::connection() in the [Monga](https://github.com/thephpleague/monga) API:

```
$cake_monga = ConnectionManager::get('mongo_db');
$mongodb = $cake_monga->connect();

// Alternatively:

$mongodb = Monga::connection($dns, $config_opts);
```

This information should help you make the bridge between instantiating the Datasource using CakePHP and utilizing the Monga API for data retrieval and saving.

### Configuration

[](#configuration)

cakephp-monga accepts all of the same options in the Datasource configuration that can be passed into the MongoClient() object in PHP. Documentation for these options is defined [here](http://php.net/manual/en/mongoclient.construct.php).

```
// In project_root/config/app.php:

'Datasources' => [

    'default' => [
        // ... Default SQL Datasource
    ],

    'mongo_db' => [
        'className' => 'CakeMonga\Database\MongoConnection',
        'logger' => null,
        'authMechanism' => null,
        'authSource' => null,
        'connect' => true,
        'connectTimeoutMS' => 60000,
        'db' => null,
        'dns' => 'mongodb://localhost:27017',
        'fsync' => null,
        'journal' => null,
        'gssapiServiceName' => 'mongodb',
        'username' => null,
        'password' => null,
        'readPreference' => null,
        'readPreferenceTags' => null,
        'replicaSet' => null,
        'secondaryAcceptableLatencyMS' => 15,
        'socketTimeoutMS' => 30000,
        'ssl' => false,
        'w' => 1,
        'wTimeoutMS' => 10000
    ]
],
```

### Connecting to a custom DNS using this library

[](#connecting-to-a-custom-dns-using-this-library)

By default, this library connects to the `mongodb://localhost:27017` DNS string. You can specify a custom DNS to connect on by setting a 'dns' key on the connection's Datasource hash in the config/app.php file:

```
// In project_root/config/app.php:

'Datasources' => [

    'mongo_db' => [
        'className' => 'CakeMonga\Database\MongoConnection',
        'dns' => 'mongodb://your.remote.host:27017'
    ]
],
```

### API and Accessing your MongoDB Instance

[](#api-and-accessing-your-mongodb-instance)

This plugin is a wrapper of the Mongo plugin by the League of Extraordinary Packages. To find out how to query, save, and update data within your Mongo collections, check out the [Monga documentation](https://github.com/thephpleague/monga).

### Defining a custom Collection class

[](#defining-a-custom-collection-class)

View the [Accessing Collections Extended Docs](https://github.com/LeWestopher/cakephp-monga/wiki/Accessing-Collections) page for more information on creating Collection classes.

As of version 0.2.0, CakeMonga supports the usage of custom Collection classes. These custom classes are located with the `src/Model/MongoCollection` folder an extend the `CakeMonga\MongoCollection\BaseCollection` class. Now you can use these classes to encapsulate data layer logic into the appropriate class locations. These methods are direct abstractions of their Monga counterparts. You can view the docs for these methods on the [Monga API Docs](https://github.com/thephpleague/monga). The `BaseCollection` class provides the following methods for data access:

```
class BaseCollection {
    public function getCollection();
    public function find($query = [], $fields = [], $findOne = false);
    public function findOne($query = [], $fields = []);
    public function drop();
    public function listIndexes();
    public function save($document, $options = []);
    public function update($values = [], $query = null, $options = []);
    public function insert(array $data, $options = []);
    public function remove($criteria, $options = []);
    public function truncate();
    public function aggregate($aggregation = []);
    public function distinct($key, $query = []);
    public function count($query = []);
}
```

Note that the MongoDB collection that is utilized by custom Collection classes is the tableized name of the Collection class itself. For example, `UsersCollection.php` would map to the `users` collection inside of your MongoDB instance.

### Retrieving a custom Collection model using CollectionRegistry

[](#retrieving-a-custom-collection-model-using-collectionregistry)

As of 0.2.0, custom Collection models extended from `BaseCollection` can be retrieved using the `CollectionRegistry` singleton with the same syntax that `TableRegistry` employs:

```
// Define a custom User collection at src/Model/MongoCollection/UserCollection.php.
use CakeMonga\MongoCollection\BaseCollection;

class UsersCollection extends BaseCollection
{
    public function getUsersNamedJohn()
    {
        return $this->find(['name' => 'John']);
    }
}

// We can retrieve this UsersCollection by using the static ::get() method on CollectionRegistry
use CakeMonga\MongoCollection\CollectionRegistry;

$users_collection = CollectionRegistry::get('Users');
```

By default, the CollectionRegistry utilizes the default connection defined as 'mongo\_db' in your app.php file. Want to use a different Mongo datasource? No problem, just pass in a datasource string to the 'connection' attribute of the config array for CollectionRegistry::get():

```
$users_collection = CollectionRegistry::get('Users', [
    'connection' => 'secondary_mongo_datasource'
]
```

This would construct the UsersCollection class with a connection to the other datasource.

### Collection Event Hooks

[](#collection-event-hooks)

As of 0.4.0, you can now define the following events on your Collection classes:

```
use CakeMonga\MongoCollection\BaseCollection;

class CustomCollection extends BaseCollection
{
    public function beforeFind($event, $query, $fields, $findOne);
    public function beforeSave($event, $document);
    public function afterSave($event, $document)
    public function beforeInsert($event, $data);
    public function afterInsert($event, $results)
    public function beforeUpdate($event, $values, $query)
    public function afterUpdate($event, $document);
    public function beforeRemove($event, $criteria);
    public function afterRemove($event, $result, $criteria);
}
```

You can find more information on Collection events on the [Accessing Collections Wiki Page](https://github.com/LeWestopher/cakephp-monga/wiki/Accessing-Collections#events)

### Custom Behaviors

[](#custom-behaviors)

As of 0.5.0, you can attach Behaviors to classes extending the BaseCollection class in the same manner that you would to a Table object. To create a custom behavior for a BaseCollection, you should extend the `MongoBehavior` class instead of the regular `Behavior` class.

You can find out more about Behaviors on collections on the [Accessing Collections Wiki Page](https://github.com/LeWestopher/cakephp-monga/wiki/Accessing-Collections#behaviors).

### Query Logging

[](#query-logging)

As of version 0.3.0, CakeMonga supports query logging via the Mongo logging context. To learn how to enable logging and create custom loggers, visit the [Query Logging Wiki Page](https://github.com/LeWestopher/cakephp-monga/wiki/Query-Logging).

### What is cakephp-monga?

[](#what-is-cakephp-monga)

This plugin is a wrapper for the popular [Monga](https://github.com/thephpleague/monga) library provided by [The League of Extraordinary packages.](https://thephpleague.com/) In it's current form, this plugin is intended to get you quickly set up and running with access to a MongoDB instance so that you can access your data in your application. This plugin provides all of the same functionality that the Monga library provides in terms of building queries and retrieving your data.

### What is cakephp-monga not?

[](#what-is-cakephp-monga-not)

This plugin is not currently intended as a drop in replacement for the SQL ORM provided by CakePHP core. While you could theoretically build an entire application using cakephp-monga as the data layer, this plugin does not have the kind of application level integration (Events, Logging, etc) that the current ORM does. Additionally, there is not abstraction layer for Database level, Collection level, or Entity level objects (EG - Defining methods on a supposed UserCollection.php, or creating a Mongo Entity at User.php), although this is on the roadmap for a future version very soon.

Additionally, it's important to recognize that while certain relational features can be emulated within a MongoDB dataset, Mongo is still not an ACID compliant database. In the future, Collection level classes will be built for object abstraction that will implement CakePHP's Repository interface, but it should be noted that full ORM features will not be supported as Mongo is not a true object relational database.

### Roadmap

[](#roadmap)

Here are some of the features that I plan on integrating into this project very soon:

- Basic Connection object support for retrieving an instance of the Monga class for simple data retrieval. **Added in 0.1.0**
- Collection and Entity level abstraction layers (EG - UserCollection.php and User.php for Mongo) **Added in 0.2.0**
- SSL Support via the stream context on the third argument of the MongoClient constructor
- Query logging via the stream context on the third argument of the MongoClient constructor **Added in 0.3.0**
- A CollectionRegistry class for retrieving Mongo collections with connection params already passed in. **Added in 0.2.0**
- Custom behavior support on the Collection level class **Added in 0.5.0**
- Events integration on the Collection level class **Added in 0.4.0**
- Validation Support

### Support

[](#support)

For bugs and feature requests, please use the [issues](https://github.com/LeWestopher/cakephp-monga/issues) section of this repository.

### Contributing

[](#contributing)

To contribute to this plugin please follow a few basic rules.

- Contributions must follow the [CakePHP coding standard](http://book.cakephp.org/3.0/en/contributing/cakephp-coding-conventions.html).
- [Unit tests](http://book.cakephp.org/3.0/en/development/testing.html) are required.

### Change Log

[](#change-log)

Yes, we have one of [those](https://github.com/LeWestopher/cakephp-monga/blob/master/CHANGELOG.md).

### Creators

[](#creators)

[Wes King](http://www.github.com/lewestopher)

[Frank de Jonge](https://github.com/frankdejonge) - Creator of the Monga Dependency

[Monga Contributors](https://github.com/thephpleague/monga/contributors)

### License

[](#license)

Copyright 2016, Wes King

Licensed under The MIT License Redistributions of files must retain the above copyright notice.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance14

Infrequent updates — may be unmaintained

Popularity24

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity56

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.

###  Release Activity

Cadence

Every ~21 days

Total

5

Last Release

3473d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4f75d8c4dbe70d9d4ef7b8092d70c8bfb5403b32c8462374ef0ccad49f9b8f6f?d=identicon)[lewestopher](/maintainers/lewestopher)

---

Top Contributors

[![LeWestopher](https://avatars.githubusercontent.com/u/5728795?v=4)](https://github.com/LeWestopher "LeWestopher (38 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/lewestopher-cakephp-monga/health.svg)

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

###  Alternatives

[laravel/browser-kit-testing

Provides backwards compatibility for BrowserKit testing in the latest Laravel release.

5139.4M285](/packages/laravel-browser-kit-testing)[cakephp/bake

Bake plugin for CakePHP

11211.2M156](/packages/cakephp-bake)[cakephp/queue

Queue plugin for CakePHP

36257.9k12](/packages/cakephp-queue)[cakephp/twig-view

Twig powered View for CakePHP

155.1M10](/packages/cakephp-twig-view)[friendsofcake/app-template

An empty CakePHP 2.5 application

721.8k](/packages/friendsofcake-app-template)[cakephp-brasil/twitter-bootstrap

TwitterBootstrap plugin for CakePHP 3

175.7k](/packages/cakephp-brasil-twitter-bootstrap)

PHPackages © 2026

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