Skip to content

Commit 8a32752

Browse files
authored
PHPLIB-987: Add more examples (#981)
* Fix include path for autoload file * Add examples for bulk writes and with_transaction * Add aggregation example * Add example for persistable objects * Ignore certain phpcs errors for all examples * Add example for deserialisation using typemap * Remove unnecessary batchSize option * Use __DIR__ instead of dirname(__FILE__) * Fix capitalisation for TypeMap * Simplify persistable example models * Add note about replica set requirements * Add note about examples to the documentation
1 parent 356b89c commit 8a32752

File tree

10 files changed

+441
-5
lines changed

10 files changed

+441
-5
lines changed

docs/index.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ following pages should help you get started:
3737

3838
- :doc:`/reference/bson`
3939

40+
Code examples can be found in the ``examples`` directory in the source code.
41+
4042
If you have previously worked with the legacy ``mongo`` extension, it will be
4143
helpful to review the :doc:`/upgrade` for a summary of API changes between the
4244
old driver and this library.

examples/aggregate.php

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace MongoDB\Examples;
5+
6+
use MongoDB\Client;
7+
8+
use function assert;
9+
use function getenv;
10+
use function is_object;
11+
use function MongoDB\BSON\fromPHP;
12+
use function MongoDB\BSON\toRelaxedExtendedJSON;
13+
use function printf;
14+
use function rand;
15+
16+
require __DIR__ . '/../vendor/autoload.php';
17+
18+
function toJSON(object $document): string
19+
{
20+
return toRelaxedExtendedJSON(fromPHP($document));
21+
}
22+
23+
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
24+
25+
$collection = $client->test->coll;
26+
$collection->drop();
27+
28+
$documents = [];
29+
30+
for ($i = 0; $i < 100; $i++) {
31+
$documents[] = ['randomValue' => rand(0, 1000)];
32+
}
33+
34+
$collection->insertMany($documents);
35+
36+
$pipeline = [
37+
[
38+
'$group' => [
39+
'_id' => null,
40+
'totalCount' => ['$sum' => 1],
41+
'evenCount' => [
42+
'$sum' => ['$mod' => ['$randomValue', 2]],
43+
],
44+
'oddCount' => [
45+
'$sum' => ['$subtract' => [1, ['$mod' => ['$randomValue', 2]]]],
46+
],
47+
'maxValue' => ['$max' => '$randomValue'],
48+
'minValue' => ['$min' => '$randomValue'],
49+
],
50+
],
51+
];
52+
53+
$cursor = $collection->aggregate($pipeline);
54+
55+
foreach ($cursor as $document) {
56+
assert(is_object($document));
57+
printf("%s\n", toJSON($document));
58+
}

examples/bulk.php

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace MongoDB\Examples;
5+
6+
use MongoDB\Client;
7+
8+
use function assert;
9+
use function getenv;
10+
use function is_object;
11+
use function MongoDB\BSON\fromPHP;
12+
use function MongoDB\BSON\toRelaxedExtendedJSON;
13+
use function printf;
14+
15+
require __DIR__ . '/../vendor/autoload.php';
16+
17+
function toJSON(object $document): string
18+
{
19+
return toRelaxedExtendedJSON(fromPHP($document));
20+
}
21+
22+
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
23+
24+
$collection = $client->test->coll;
25+
$collection->drop();
26+
27+
$documents = [];
28+
29+
for ($i = 0; $i < 10; $i++) {
30+
$documents[] = ['x' => $i];
31+
}
32+
33+
$collection->insertMany($documents);
34+
35+
$collection->bulkWrite(
36+
[
37+
[
38+
'deleteMany' => [
39+
['x' => ['$gt' => 7]], // Filter
40+
],
41+
],
42+
[
43+
'deleteOne' => [
44+
['x' => 4], // Filter
45+
],
46+
],
47+
[
48+
'replaceOne' => [
49+
['x' => 1], // Filter
50+
['y' => 1], // Replacement
51+
],
52+
],
53+
[
54+
'updateMany' => [
55+
['x' => ['$gt' => 5]], // Filter
56+
['$set' => ['updateMany' => true]], // Update
57+
],
58+
],
59+
[
60+
'updateOne' => [
61+
['x' => 2], // Filter
62+
['$set' => ['y' => 2]], // Update
63+
],
64+
],
65+
[
66+
'insertOne' => [
67+
['x' => 10], // Document
68+
],
69+
],
70+
]
71+
);
72+
73+
$cursor = $collection->find([]);
74+
75+
foreach ($cursor as $document) {
76+
assert(is_object($document));
77+
printf("%s\n", toJSON($document));
78+
}

examples/changestream.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33

44
namespace MongoDB\Examples;
55

6-
require '../vendor/autoload.php';
7-
86
use MongoDB\Client;
97

108
use function assert;
@@ -18,11 +16,14 @@
1816

1917
use const STDERR;
2018

19+
require __DIR__ . '/../vendor/autoload.php';
20+
2121
function toJSON(object $document): string
2222
{
2323
return toRelaxedExtendedJSON(fromPHP($document));
2424
}
2525

26+
// Change streams require a replica set or sharded cluster
2627
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
2728

2829
$collection = $client->test->coll;

examples/command_logger.php

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33

44
namespace MongoDB\Examples;
55

6-
require '../vendor/autoload.php';
7-
86
use MongoDB\Client;
97
use MongoDB\Driver\Monitoring\CommandFailedEvent;
108
use MongoDB\Driver\Monitoring\CommandStartedEvent;
@@ -22,12 +20,13 @@
2220

2321
use const STDERR;
2422

23+
require __DIR__ . '/../vendor/autoload.php';
24+
2525
function toJSON(object $document): string
2626
{
2727
return toRelaxedExtendedJSON(fromPHP($document));
2828
}
2929

30-
// phpcs:disable Squiz.Classes.ClassFileName.NoMatch
3130
class CommandLogger implements CommandSubscriber
3231
{
3332
public function commandStarted(CommandStartedEvent $event): void

examples/persistable.php

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace MongoDB\Examples;
5+
6+
use MongoDB\BSON\ObjectId;
7+
use MongoDB\BSON\Persistable;
8+
use MongoDB\Client;
9+
use MongoDB\Model\BSONArray;
10+
use UnexpectedValueException;
11+
12+
use function getenv;
13+
use function var_dump;
14+
15+
require __DIR__ . '/../vendor/autoload.php';
16+
17+
class PersistableEntry implements Persistable
18+
{
19+
/** @var ObjectId */
20+
private $id;
21+
22+
/** @var string */
23+
public $name;
24+
25+
/** @var array<PersistableEmail> */
26+
public $emails = [];
27+
28+
public function __construct(string $name)
29+
{
30+
$this->id = new ObjectId();
31+
$this->name = $name;
32+
}
33+
34+
public function getId(): ObjectId
35+
{
36+
return $this->id;
37+
}
38+
39+
public function bsonSerialize(): object
40+
{
41+
return (object) [
42+
'_id' => $this->id,
43+
'name' => $this->name,
44+
'emails' => $this->emails,
45+
];
46+
}
47+
48+
public function bsonUnserialize(array $data): void
49+
{
50+
if (! $data['_id'] instanceof ObjectId) {
51+
throw new UnexpectedValueException('_id field is not of the expected type');
52+
}
53+
54+
if (! $data['emails'] instanceof BSONArray) {
55+
throw new UnexpectedValueException('emails field is not of the expected type');
56+
}
57+
58+
$this->id = $data['_id'];
59+
$this->name = (string) $data['name'];
60+
61+
/** @psalm-suppress MixedPropertyTypeCoercion */
62+
$this->emails = $data['emails']->getArrayCopy(); // Emails will be passed as a BSONArray instance
63+
}
64+
}
65+
66+
class PersistableEmail implements Persistable
67+
{
68+
/** @var string */
69+
public $type;
70+
71+
/** @var string */
72+
public $address;
73+
74+
public function __construct(string $type, string $address)
75+
{
76+
$this->type = $type;
77+
$this->address = $address;
78+
}
79+
80+
public function bsonSerialize(): object
81+
{
82+
return (object) [
83+
'type' => $this->type,
84+
'address' => $this->address,
85+
];
86+
}
87+
88+
public function bsonUnserialize(array $data): void
89+
{
90+
$this->type = (string) $data['type'];
91+
$this->address = (string) $data['address'];
92+
}
93+
}
94+
95+
$entry = new PersistableEntry('alcaeus');
96+
$entry->emails[] = new PersistableEmail('work', 'alcaeus@example.com');
97+
$entry->emails[] = new PersistableEmail('private', 'secret@example.com');
98+
99+
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
100+
101+
$collection = $client->test->coll;
102+
$collection->drop();
103+
104+
$collection->insertOne($entry);
105+
106+
$foundEntry = $collection->findOne([]);
107+
108+
/** @psalm-suppress ForbiddenCode */
109+
var_dump($foundEntry);

0 commit comments

Comments
 (0)