PHPackages                             pcmnac/mongoyii-php7 - 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. pcmnac/mongoyii-php7

ActiveYii-extension[Database &amp; ORM](/categories/database)

pcmnac/mongoyii-php7
====================

A Yii MongoDB ORM for PHP7

3.0.1(7y ago)014BSD-3-ClausePHP

Since Mar 21Pushed 7y ago1 watchersCompare

[ Source](https://github.com/pcmnac/mongoyii-php7)[ Packagist](https://packagist.org/packages/pcmnac/mongoyii-php7)[ RSS](/packages/pcmnac-mongoyii-php7/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (1)Versions (21)Used By (0)

MongoYii-php7
=============

[](#mongoyii-php7)

A PHP7 edition of [mongoyii](http://sammaye.github.io/MongoYii) designed for and working with the [new MongoDB driver](http://php.net/manual/en/set.mongodb.php)

About this Documentation
------------------------

[](#about-this-documentation)

This is not a complete rewrite of the old documentation, instead it will only detail the new features/ideas behind the PHP7 extension.

[Please read the old documentation first if you are new to mongoyii](http://sammaye.github.io/MongoYii).

Test Application
----------------

[](#test-application)

There is a new test application for this extension which is a rewrite of the old test appliction.

[You can find it over here](https://github.com/Sammaye/mongoyii-php7-test).

Running the inbuilt tests are the same as before.

Issues/Bugs &amp; Questions
---------------------------

[](#issuesbugs--questions)

Please use the new Github issue tracker for all your questions and bug reports. If you post in the forums please link it in the Github issue tracker.

[You can access the Github issue tracker here](https://github.com/Sammaye/mongoyii-php7/issues).

Versioning
----------

[](#versioning)

This extension, like the previous, uses [semantic versioning 2.0.0](http://semver.org/).

Licence
-------

[](#licence)

The licence for this extension remains the same as well, [BSD 3 clause](http://opensource.org/licenses/BSD-3-Clause). To make it short and to the point: do whatever you want with it.

Note About Changes
------------------

[](#note-about-changes)

Before I go into what has changed in this extension it is good to note that many of the changes are not because of my wanting to make them but because the MongoDB driver and PHPLib they have released has changed the workings so dramatically from the old drivers that I was forced to conform to this new standard of working.

There are some parts of the driver and it's PHPLib you will like and others you definitely wont.

Installling
-----------

[](#installling)

All installling is now done through composer. I would NOT recommend installing manually since this extension requires both the driver and the PHPLib MongoDB has released to go with it (which is only on composer as well).

To install simply do (for `dev-master`):

```
composer require sammaye/mongoyii-php7:*

```

[You can find the packagist repository here](https://packagist.org/packages/sammaye/mongoyii-php7).

Namespacing
-----------

[](#namespacing)

This extension is fully namespaced as:

```
sammaye\mongoyii

```

Do not worry! This does not make for too many changes for old applications. It took me about 3 hours to rewrite my test application.

For example, here is how to declare a new model (taken from my test application):

```
use MongoDB\BSON\ObjectID;
use MongoDB\BSON\UTCDateTime;

use sammaye\mongoyii\Document;

/**
 * Represents the article itself, and all of its data
 */
class Article extends Document
{
}
```

And that will give you all the same stuff as before.

Now let me show you an example of configuring the `session` and `cache` component in your `main.php` (again, taken from my test application):

```
'session' => array(
	'class' => 'sammaye\mongoyii\util\Session',
),
'cache' => array(
	'class' => 'sammaye\mongoyii\util\Cache',
),
```

So you see use of the namespaces is very easy to get to grips with.

As a final example, let's take a behaviour:

```
public function behaviors()
{
	return [
		'TimestampBehavior' => [
			'class' => 'sammaye\mongoyii\behaviors\TimestampBehavior'
			// adds a nice create_time and update_time Mongodate to our docs
		]
	];
}
```

So, you see: using namespaces in this extension is very easy. If ever in doubt which namespace to use look up the file in your project and look at the first line where it says something like:

```
namespace sammaye\mongoyii\validators;
```

Add the class name to that and you have your namespace class.

Declaring the Extension
-----------------------

[](#declaring-the-extension)

This is easily the part that has changed the most. To start off, why don't I show an example I use:

```
'mongodb' => [
	'class' => 'sammaye\mongoyii\Client',
	'uri' => 'mongodb://sam:blah@localhost:27017/admin',
	'options' => [],
	'driverOptions' => [],
	'db' => [
		'super_test' => [
			'writeConcern' => new WriteConcern(1),
			'readPreference' => new ReadPreference(ReadPreference::RP_PRIMARY),
		]
	],
	'enableProfiling' => true
],
```

Now, let's break this down:

- I delcare the class as `sammaye\mongoyii\Client`. This is required and will not be variable.
- The `uri` is my server connection string and follows the standard laid out in the [PHP documentation](http://php.net/manual/en/mongodb-driver-manager.construct.php)
- The `options` directly relate to the `uri` options in the [PHP documentation](http://php.net/manual/en/mongodb-driver-manager.construct.php) as well, allowing replica set connections etc
- And the same goes for driver options which are also in the [PHP documentation](http://php.net/manual/en/mongodb-driver-manager.construct.php)
- `enableProfiling` allows you to profile your queries as before
- `db` has now changed to be an array indexed by the names of the databases you wish to connect to. The value of each index being the options for the [PHPLib `Database` object](https://github.com/mongodb/mongo-php-library/blob/master/src/Database.php)

And that is basically it. The write concern, read concern, and other properties are now done per database as you see instead of on client level.

If you have other databases in your configuration and want to set a specific one as default you can add the `active` option as shown:

```
'super_test' => [
	'writeConcern' => new WriteConcern(1),
	'readPreference' => new ReadPreference(ReadPreference::RP_PRIMARY),
	'active' => true
]
```

### The Client `__get` Only Gets a Database?

[](#the-client-__get-only-gets-a-database)

Yes, this is the biggest change between the old driver and the new one.

There is now a clear separation between the client, database, and collection.

So to get the database, ready for fetching a collection you now need to do:

```
Yii::$app->mongodb->selectDatabase()
```

### Authentication

[](#authentication)

In the new PHP driver there is no `auth()` function. You must athenticate within the `uri` of the `mongodb` component. You will decide how best to sort out your authentication database but I decided to put all users into the `admin` database. This makes it incredibly easy to authenticate to one database and then switch as I need.

### Using Multiple Databases

[](#using-multiple-databases)

As you can see, this extension takes multiple databases into account.

If you are using authentication make sure you either layout your users in a way that means you only need one socket connection (like I have above) or make a new component for each time you need to authenticate. You cannot authenticate AFTER connecting anymore.

As for recoding the `Document`'s `getDbConnection()` you now use `getCollection()`like so (due to the separation I mentioned above):

```
public function getCollection()
{
	return $this
		->getDbConnection()
		->selectDatabase('my_other_db_not_default')
		->{$this->collectionName()};
}
```

And you are done...

If you really know what you are doing you can actually set a database as `active` making it default for a set of procedures:

```
Yii::$app->mongodb->selectDatabase('my_other_db', ['active' => true]);
```

But this is for advanced users only!

Querying
--------

[](#querying)

This is the biggest change away from Yii1. Everything else remains the same and does not require documenting.

Basically, due to how the new driver no longer uses cursors but instead streams I have recoded the `EMongoDBCriteria` object to be `Query` (like in Yii2) and it even works similar to how it does in Yii2.

However, it is good to note that the `Document` functions of `find()` and `findOne()`return the same as they do in normal Yii1. The return there has not changed.

It is good to note that the way to query has changed though, in accordance with the driver:

```
Article::find(
	[
		'title' => 'Test'
	],
	[
		'sort' => ['date_created' => -1],
		'limit' => 2
		// etc
	]
)
```

This is due to how MongoDB uses eager loaded streams. As such the entire query must be defined BEFORE forming the PHP "cursor" object now.

A good place to understand how to query using the new driver is to look at the Github documentation for the [MongoDB PHPLib](http://mongodb.github.io/mongo-php-library/classes/collection/).

### Scopes

[](#scopes)

Due to the change in the `EMongoCriteria` you may need to rewrite model scopes for them to work. A good example would be:

```
[
	'condition' => ['deleted' => 0],
	'select' => ['_id' => 1],
	'sort' => ['date' => -1],
	'limit' => 2
	'skip' => 1
]
```

There is not a lot of changes you will see publicly, the biggest one is that I do not use the `project` word anymore for `SELECT` in SQL. MongoDB still does but I don't.

### Why No EMongoCriteria?

[](#why-no-emongocriteria)

This was a decision put forward by the need to produce clean and workable querying.

I decided, in the end, to make my querying more like Yii2. This actually means you can do this now:

```
$docs = new Query([
	'from' => 'colllection',
	'condition' => ['what' => 'ever'],
	'limit' => 1
])->all()
```

So, it is a break from Yii1 to Yii2 but it is a good break.

### Query Logging

[](#query-logging)

Query logging is now much more extensive. Instead of just logging queries through the models it will now log all queries thanks to a small rewrite which should have been in the original extension.

Now, whenever you get the collection from the MongoDB component in your configuration it will return my own custom `Collection` class which has logging tied into it.

Hopefully, this should take some of the guess work out of building applications.

Notes About Quirks
------------------

[](#notes-about-quirks)

### Subdocuments

[](#subdocuments)

The MongoDB driver's PHPLib returns subdocuments as `ArrayObject`s. This means you need to type cast them via `(array)$subdoc` first before you use them in display and forms etc.

### BSON Serialisation

[](#bson-serialisation)

Make sure you do not use `ObjectID` as your yii session ID. This is because of this [issue whereby you cannot serialise BSON objects yet](https://jira.mongodb.org/browse/PHPC-460).

As an exmaple, here is a potential `UserIdentity` `authenticate()` method you can use (taken from my example application too):

```
public function authenticate()
{
	$record=User::model()->findOne(array('username' => $this->username));
	if ($record === null) {
		$this->errorCode = self::ERROR_USERNAME_INVALID;
	} else if ($record->password !== crypt($this->password, $record->password)) { // check crypted password against the one provided
		$this->errorCode = self::ERROR_PASSWORD_INVALID;
	} else {
		$this->_id = (String)$record->_id;
		$this->errorCode = self::ERROR_NONE;
	}
	return !$this->errorCode;
}
```

Notice the line: `$this->_id = (String)$record->_id;` it is extremely important or else nothing will work!

### `DBRef` is Deprecated

[](#dbref-is-deprecated)

Yep, it is. If you are using it you will need to get rid of it before using this extension. There is simply no functionality for handling it in the new driver.

Stuff Not Done
--------------

[](#stuff-not-done)

### GridFS

[](#gridfs)

Not my fault. It is actually not there yet in the PHPLib!

And We Are... Done!
-------------------

[](#and-we-are-done)

That should be it. Everything else is pretty much the same, cool, huh?

Please, do let me know if I have left anything out or need to explain something better.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 71.2% 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 ~52 days

Recently: every ~83 days

Total

20

Last Release

2709d ago

Major Versions

1.1.4 → 2.0.02017-01-09

2.0.5 → 3.0.02018-12-14

### Community

Maintainers

![](https://www.gravatar.com/avatar/44b60d7d6c8dda65a0f8092984914b8b94d2e1727e7fbc49d42126a41b77277c?d=identicon)[pcmnac](/maintainers/pcmnac)

---

Top Contributors

[![Sammaye](https://avatars.githubusercontent.com/u/323996?v=4)](https://github.com/Sammaye "Sammaye (42 commits)")[![Kuzdo](https://avatars.githubusercontent.com/u/6685335?v=4)](https://github.com/Kuzdo "Kuzdo (4 commits)")[![pcmnac](https://avatars.githubusercontent.com/u/2421641?v=4)](https://github.com/pcmnac "pcmnac (4 commits)")[![dsphper](https://avatars.githubusercontent.com/u/10858759?v=4)](https://github.com/dsphper "dsphper (3 commits)")[![bashkarev](https://avatars.githubusercontent.com/u/3738201?v=4)](https://github.com/bashkarev "bashkarev (2 commits)")[![devonliu02](https://avatars.githubusercontent.com/u/4284940?v=4)](https://github.com/devonliu02 "devonliu02 (2 commits)")[![jorgerobles](https://avatars.githubusercontent.com/u/1706080?v=4)](https://github.com/jorgerobles "jorgerobles (1 commits)")[![pmoust](https://avatars.githubusercontent.com/u/2493339?v=4)](https://github.com/pmoust "pmoust (1 commits)")

---

Tags

ormmongodbyiiPHP7

### Embed Badge

![Health badge](/badges/pcmnac-mongoyii-php7/health.svg)

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

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[sammaye/mongoyii-php7

A Yii MongoDB ORM for PHP7

2042.0k1](/packages/sammaye-mongoyii-php7)[omines/datatables-bundle

Symfony DataTables Bundle with native Doctrine ORM, Elastica and MongoDB support

2851.4M6](/packages/omines-datatables-bundle)[sammaye/mongoyii

A Yii MongoDB ORM

13681.3k](/packages/sammaye-mongoyii)[mmucklo/queue-bundle

Symfony2/3/4/5 Queue Bundle (for background jobs) supporting Mongo (Doctrine ODM), Mysql (and any Doctrine ORM), RabbitMQ, Beanstalkd, Redis, and ... {write your own}

120839.8k](/packages/mmucklo-queue-bundle)[sokil/php-mongo

PHP Object Document Mapper for MongoDB

239161.5k9](/packages/sokil-php-mongo)

PHPackages © 2026

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