Skip to content

Commit 8a261d0

Browse files
committed
Implement write helper
1 parent 02db0fc commit 8a261d0

File tree

2 files changed

+72
-1
lines changed

2 files changed

+72
-1
lines changed

examples/write.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
require __DIR__ . "/../src/Collection.php";
4+
5+
6+
$manager = new MongoDB\Manager("mongodb://localhost:27017");
7+
8+
9+
$collection = new MongoDB\Collection($manager, "crud.examples");
10+
$hannes = array(
11+
"name" => "Hannes",
12+
"nick" => "bjori",
13+
"citizen" => "Iceland",
14+
);
15+
$hayley = array(
16+
"name" => "Hayley",
17+
"nick" => "Alien Ninja",
18+
"citizen" => "USA",
19+
);
20+
$jonpall = array(
21+
"name" => "Jon Pall",
22+
"nick" => "unknown",
23+
"citizen" => "Iceland",
24+
);
25+
26+
try {
27+
$hannes_id = $collection->insertOne($hannes);
28+
} catch(Exception $e) {
29+
echo $e->getMessage(), "\n";
30+
exit;
31+
}
32+
33+
try {
34+
$results = $collection->insertMany(array($hayley, $jonpall));
35+
} catch(Exception $e) {
36+
echo $e->getMessage(), "\n";
37+
exit;
38+
}
39+
40+
41+

src/Collection.php

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
use MongoDB\Manager;
55
use MongoDB\Query;
66
use MongoDB\ReadPreference;
7+
use MongoDB\WriteBatch;
78

89
class QueryFlags {
910
const TAILABLE_CURSOR = 0x02;
@@ -22,6 +23,10 @@ class CursorType {
2223
}
2324

2425
class Collection {
26+
const INSERT = 0x01;
27+
const UPDATE = 0x02;
28+
const DELETE = 0x04;
29+
2530
protected $manager;
2631
protected $rp;
2732
protected $wc;
@@ -167,6 +172,31 @@ protected function _buildQuery($document, $options) { /* {{{ */
167172
return $query;
168173
} /* }}} */
169174
/* }}} */
170-
}
175+
176+
protected function _writeSingle($filter, $type, array $options = array(), $newobj = array()) { /* {{{ */
177+
$options = array_merge($this->getWriteOptions(), $options);
178+
179+
$batch = new WriteBatch($options["ordered"]);
180+
switch($type) {
181+
case self::INSERT:
182+
$batch->insert($filter);
183+
break;
184+
185+
case self::DELETE:
186+
$batch->delete($filter, $options);
187+
break;
188+
189+
case self::UPDATE:
190+
$batch->update($filter, $newobj, $options);
191+
break;
192+
}
193+
194+
return $this->manager->executeWriteBatch($this->ns, $batch, $this->wc);
195+
} /* }}} */
196+
function getWriteOptions() { /* {{{ */
197+
return array(
198+
"ordered" => false,
199+
);
200+
} /* }}} */
171201
}
172202

0 commit comments

Comments
 (0)