Skip to content

Commit 780026f

Browse files
committed
Add examples on gridfs
1 parent 92e0a10 commit 780026f

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

examples/gridfs-stream.php

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
3+
/**
4+
* This example demonstrates how to use GridFS streams.
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
namespace MongoDB\Examples;
10+
11+
use MongoDB\Client;
12+
13+
use function fclose;
14+
use function feof;
15+
use function fread;
16+
use function fwrite;
17+
use function getenv;
18+
use function strlen;
19+
20+
use const PHP_EOL;
21+
22+
require __DIR__ . '/../vendor/autoload.php';
23+
24+
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
25+
26+
$bucket = $client->test->selectGridFSBucket(['disableMD5' => true]);
27+
28+
// Open a stream for writing, similar to fopen with mode 'w'
29+
$stream = $bucket->openUploadStream('hello.txt');
30+
31+
for ($i = 0; $i < 1_000_000; $i++) {
32+
fwrite($stream, 'Hello line ' . $i . PHP_EOL);
33+
}
34+
35+
// Last data are flushed to the server when the stream is closed
36+
fclose($stream);
37+
38+
// Open a stream for reading, similar to fopen with mode 'r'
39+
$stream = $bucket->openDownloadStreamByName('hello.txt');
40+
41+
$size = 0;
42+
while (! feof($stream)) {
43+
$data = fread($stream, 2 ** 10);
44+
$size += strlen($data);
45+
}
46+
47+
echo 'Read a total of ' . $size . ' bytes' . PHP_EOL;

examples/gridfs-upload.php

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
3+
/**
4+
* This example demonstrates how to upload and download files from a stream with GridFS.
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
namespace MongoDB\Examples;
10+
11+
use MongoDB\BSON\ObjectId;
12+
use MongoDB\Client;
13+
14+
use function assert;
15+
use function fclose;
16+
use function fopen;
17+
use function fwrite;
18+
use function getenv;
19+
use function rewind;
20+
21+
use const PHP_EOL;
22+
use const STDOUT;
23+
24+
require __DIR__ . '/../vendor/autoload.php';
25+
26+
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
27+
28+
$gridfs = $client->selectDatabase('test')->selectGridFSBucket();
29+
30+
// Create an in-memory stream, this can be any stream source like STDIN or php://input for web requests
31+
$stream = fopen('php://temp', 'w+');
32+
fwrite($stream, 'Hello world!');
33+
rewind($stream);
34+
35+
// Upload to GridFS from the stream
36+
$id = $gridfs->uploadFromStream('hello.txt', $stream);
37+
assert($id instanceof ObjectId);
38+
echo 'Inserted file with ID: ' . $id . PHP_EOL;
39+
fclose($stream);
40+
41+
// Download the file and print the contents directly to STDOUT
42+
echo 'File contents: ';
43+
$gridfs->downloadToStreamByName('hello.txt', STDOUT);
44+
echo PHP_EOL;
45+
46+
// Delete the file
47+
$gridfs->delete($id);

0 commit comments

Comments
 (0)