README.md 6.07 KB
Newer Older
Qiang Xue committed
1 2
MongoDb Extension for Yii 2
===========================
3

Qiang Xue committed
4
This extension provides the [MongoDB](http://www.mongodb.org/) integration for the Yii2 framework.
5 6 7 8 9


Installation
------------

Qiang Xue committed
10 11
This extension requires [MongoDB PHP Extension](http://us1.php.net/manual/en/book.mongo.php) version 1.3.0 or higher.

12 13 14
The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run
Qiang Xue committed
15

16
```
17
php composer.phar require --prefer-dist yiisoft/yii2-mongodb "*"
18 19 20
```

or add
Qiang Xue committed
21

22
```
23
"yiisoft/yii2-mongodb": "*"
24 25
```

Qiang Xue committed
26
to the require section of your composer.json.
27 28


29 30
General Usage
-------------
31

32 33 34 35 36 37
To use this extension, simply add the following code in your application configuration:

```php
return [
	//....
	'components' => [
38 39
		'mongodb' => [
			'class' => '\yii\mongodb\Connection',
40 41 42 43 44 45
			'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
		],
	],
];
```

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
Using the connection instance you may access databases and collections.
Most of the MongoDB commands are accessible via [[\yii\mongodb\Collection]] instance:

```php
$collection = Yii::$app->mongodb->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);
```

To perform "find" queries, you should use [[\yii\mongodb\Query]]:

```php
use yii\mongodb\Query;

$query = new Query;
// compose the query
$query->select(['name', 'status'])
	->from('customer')
	->limit(10);
// execute the query
$rows = $query->all();
```

This extension supports logging and profiling, however log messages does not contain
actual text of the performed queries, they contains only a “close approximation” of it
composed on the values which can be extracted from PHP Mongo extension classes.
If you need to see actual query text, you should use specific tools for that.


Notes about MongoId
-------------------

Remember: MongoDB document id ("_id" field) is not scalar, but an instance of [[\MongoId]] class.
To get actual Mongo ID string your should typecast [[\MongoId]] instance to string:

```php
$query = new Query;
$row = $query->from('customer')->one();
var_dump($row['_id']); // outputs: "object(MongoId)"
var_dump((string)$row['_id']); // outputs "string 'acdfgdacdhcbdafa'"
```

Although this fact is very useful sometimes, it often produces some problems.
You may face them in URL composition or attempt of saving "_id" to other storage.
In these cases, ensure you have converted [[\MongoId]] into the string:

```php
/** @var yii\web\View $this */
93
echo $this->createUrl(['item/update', 'id' => (string)$row['_id']]);
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
```

While building condition, values for the key '_id' will be automatically cast to [[\MongoId]] instance,
even if they are plain strings. So it is not necessary for you to perform back cast of string '_id'
representation:

```php
use yii\web\Controller;
use yii\mongodb\Query;

class ItemController extends Controller
{
	/**
	 * @param string $id MongoId string (not object)
	 */
	public function actionUpdate($id)
	{
		$query = new Query;
		$row = $query->from('item')
			where(['_id' => $id]) // implicit typecast to [[\MongoId]]
			->one();
		...
	}
}
```

However, if you have other columns, containing [[\MongoId]], you
should take care of possible typecast on your own.


Using the MongoDB ActiveRecord
------------------------------

127
This extension provides ActiveRecord solution similar ot the [[\yii\db\ActiveRecord]].
128
To declare an ActiveRecord class you need to extend [[\yii\mongodb\ActiveRecord]] and
129 130 131
implement the `collectionName` and 'attributes' methods:

```php
132
use yii\mongodb\ActiveRecord;
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

class Customer extends ActiveRecord
{
	/**
	 * @return string the name of the index associated with this ActiveRecord class.
	 */
	public static function collectionName()
	{
		return 'customer';
	}

	/**
	 * @return array list of attribute names.
	 */
	public function attributes()
	{
Klimov Paul committed
149
		return ['_id', 'name', 'email', 'address', 'status'];
150 151 152 153
	}
}
```

Klimov Paul committed
154 155
Note: collection primary key name ('_id') should be always explicitly setup as an attribute.

Qiang Xue committed
156
You can use [[\yii\data\ActiveDataProvider]] with [[\yii\mongodb\Query]] and [[\yii\mongodb\ActiveQuery]]:
157 158 159

```php
use yii\data\ActiveDataProvider;
160
use yii\mongodb\Query;
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

$query = new Query;
$query->from('customer')->where(['status' => 2]);
$provider = new ActiveDataProvider([
	'query' => $query,
	'pagination' => [
		'pageSize' => 10,
	]
]);
$models = $provider->getModels();
```

```php
use yii\data\ActiveDataProvider;
use app\models\Customer;

$provider = new ActiveDataProvider([
	'query' => Customer::find(),
	'pagination' => [
		'pageSize' => 10,
	]
]);
$models = $provider->getModels();
```

186

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
Working with embedded documents
-------------------------------

This extension does not provide any special way to work with embedded documents (sub-documents).
General recommendation is avoiding it if possible.
For example: instead of:

```
{
	content: "some content",
	author: {
		name: author1,
		email: author1@domain.com
	}
}
```

use following:

```
{
	content: "some content",
	author_name: author1,
	author_email: author1@domain.com
}
```

Yii Model designed assuming single attribute is a scalar. Validation and attribute processing based on this suggestion.
Still any attribute can be an array of any depth and complexity, however you should handle its validation on your own.


218 219 220
Using GridFS
------------

221
This extension supports [MongoGridFS](http://docs.mongodb.org/manual/core/gridfs/) via
Qiang Xue committed
222
classes under namespace "\yii\mongodb\file".
223
There you will find specific Collection, Query and ActiveRecord classes.
Klimov Paul committed
224

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

Using the Cache component
-------------------------

To use the `Cache` component, in addition to configuring the connection as described above,
you also have to configure the `cache` component to be `yii\mongodb\Cache`:

```php
return [
	//....
	'components' => [
		// ...
		'cache' => [
			'class' => 'yii\mongodb\Cache',
		],
	]
];
```


Using the Session component
---------------------------

To use the `Session` component, in addition to configuring the connection as described above,
you also have to configure the `session` component to be `yii\mongodb\Session`:

```php
return [
	//....
	'components' => [
		// ...
		'session' => [
			'class' => 'yii\mongodb\Session',
		],
	]
];
```