Skip to content

Commit

Permalink
Add examples on gridfs
Browse files Browse the repository at this point in the history
  • Loading branch information
GromNaN committed Jan 4, 2024
1 parent 92e0a10 commit c0cd6f3
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
47 changes: 47 additions & 0 deletions examples/gridfs-stream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/**
* This example demonstrates how to use GridFS streams.
*/

declare(strict_types=1);

namespace MongoDB\Examples;

use MongoDB\Client;

use function fclose;
use function feof;
use function fread;
use function fwrite;
use function getenv;
use function strlen;

use const PHP_EOL;

require __DIR__ . '/../vendor/autoload.php';

$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');

$bucket = $client->test->selectGridFSBucket(['disableMD5' => true]);

// Open a stream for writing, similar to fopen with mode 'w'
$stream = $bucket->openUploadStream('hello.txt');

for ($i = 0; $i < 1_000_000; $i++) {
fwrite($stream, 'Hello line ' . $i . PHP_EOL);
}

// Last data are flushed to the server when the stream is closed
fclose($stream);

// Open a stream for reading, similar to fopen with mode 'r'
$stream = $bucket->openDownloadStreamByName('hello.txt');

$size = 0;
while (! feof($stream)) {
$data = fread($stream, 2 ** 10);
$size += strlen($data);
}

echo 'Read a total of ' . $size . ' bytes' . PHP_EOL;
47 changes: 47 additions & 0 deletions examples/gridfs-upload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/**
* This example demonstrates how to upload and download files from a stream with GridFS.
*/

declare(strict_types=1);

namespace MongoDB\Examples;

use MongoDB\BSON\ObjectId;
use MongoDB\Client;

use function assert;
use function fclose;
use function fopen;
use function fwrite;
use function getenv;
use function rewind;

use const PHP_EOL;
use const STDOUT;

require __DIR__ . '/../vendor/autoload.php';

$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');

$gridfs = $client->selectDatabase('test')->selectGridFSBucket();

// Create an in-memory stream, this can be any stream source like STDIN or php://input for web requests
$stream = fopen('php://temp', 'w+');
fwrite($stream, 'Hello world!');
rewind($stream);

// Upload to GridFS from the stream
$id = $gridfs->uploadFromStream('hello.txt', $stream);
assert($id instanceof ObjectId);
echo 'Inserted file with ID: ' . $id . PHP_EOL;
fclose($stream);

// Download the file and print the contents directly to STDOUT, chunk by chunk
echo 'File contents: ';
$gridfs->downloadToStreamByName('hello.txt', STDOUT);
echo PHP_EOL;

// Delete the file
$gridfs->delete($id);

0 comments on commit c0cd6f3

Please sign in to comment.