Skip to content

PHPLIB-1248 Add examples on GridFS #1196

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
54 changes: 54 additions & 0 deletions examples/gridfs_stream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

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

declare(strict_types=1);

namespace MongoDB\Examples;

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

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

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

$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
// Disable MD5 computation for faster uploads, this feature is deprecated
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I explicitly disabled MD5, that's what developers should do in their applications.

$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 . "\n");
}

// 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' . "\n";

// Retrieve the file ID to delete it
$id = $bucket->getFileIdForStream($stream);
assert($id instanceof ObjectId);
$bucket->delete($id);

echo 'Deleted file with ID: ' . $id . "\n";
Original file line number Diff line number Diff line change
Expand Up @@ -18,42 +18,41 @@
use function getenv;
use function stream_context_create;

use const PHP_EOL;

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

$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
$bucket = $client->test->selectGridFSBucket();
// Disable MD5 computation for faster uploads, this feature is deprecated
$bucket = $client->test->selectGridFSBucket(['disableMD5' => true]);
$bucket->drop();

// Register the alias "mybucket" for default bucket of the "test" database
$bucket->registerGlobalStreamWrapperAlias('mybucket');

echo 'File exists: ';
echo file_exists('gridfs://mybucket/hello.txt') ? 'yes' : 'no';
echo PHP_EOL;
echo "\n";

echo 'Writing file';
file_put_contents('gridfs://mybucket/hello.txt', 'Hello, GridFS!');
echo PHP_EOL;
echo "\n";

echo 'File exists: ';
echo file_exists('gridfs://mybucket/hello.txt') ? 'yes' : 'no';
echo PHP_EOL;
echo "\n";

echo 'Reading file: ';
echo file_get_contents('gridfs://mybucket/hello.txt');
echo PHP_EOL;
echo "\n";

echo 'Writing new version of the file';
file_put_contents('gridfs://mybucket/hello.txt', 'Hello, GridFS! (v2)');
echo PHP_EOL;
echo "\n";

echo 'Reading new version of the file: ';
echo file_get_contents('gridfs://mybucket/hello.txt');
echo PHP_EOL;
echo "\n";

echo 'Reading previous version of the file: ';
$context = stream_context_create(['gridfs' => ['revision' => -2]]);
echo file_get_contents('gridfs://mybucket/hello.txt', false, $context);
echo PHP_EOL;
echo "\n";
49 changes: 49 additions & 0 deletions examples/gridfs_upload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?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 function stream_get_contents;

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

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

// Disable MD5 computation for faster uploads, this feature is deprecated
$gridfs = $client->test->selectGridFSBucket(['disableMD5' => true]);

// 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, "\n";
fclose($stream);

// Download the file and print the contents directly to an in-memory stream, chunk by chunk
$stream = fopen('php://temp', 'w+');
$gridfs->downloadToStreamByName('hello.txt', $stream);
rewind($stream);
echo 'File contents: ', stream_get_contents($stream), "\n";

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

echo 'Deleted file with ID: ', $id, "\n";
2 changes: 1 addition & 1 deletion psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<code><![CDATA[$clientEncryption->decrypt($document->encryptedField)]]></code>
</MixedArgument>
</file>
<file src="examples/atlas-search.php">
<file src="examples/atlas_search.php">
<MixedArgument>
<code><![CDATA[$document['name']]]></code>
<code><![CDATA[$index->name]]></code>
Expand Down
28 changes: 25 additions & 3 deletions tests/ExamplesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,28 @@ public static function provideExamples(): Generator
'expectedOutput' => $expectedOutput,
];

$expectedOutput = <<<'OUTPUT'
Read a total of 17888890 bytes
Deleted file with ID: %s
OUTPUT;

yield 'gridfs_stream' => [
'file' => __DIR__ . '/../examples/gridfs_stream.php',
'expectedOutput' => $expectedOutput,
];

$expectedOutput = <<<'OUTPUT'
Inserted file with ID: %s
File contents: Hello world!
Deleted file with ID: %s

OUTPUT;

yield 'gridfs_upload' => [
'file' => __DIR__ . '/../examples/gridfs_upload.php',
'expectedOutput' => $expectedOutput,
];

$expectedOutput = <<<'OUTPUT'
File exists: no
Writing file
Expand All @@ -109,8 +131,8 @@ public static function provideExamples(): Generator
Reading previous version of the file: Hello, GridFS!
OUTPUT;

yield 'gridfs-stream-wrapper' => [
'file' => __DIR__ . '/../examples/gridfs-stream-wrapper.php',
yield 'gridfs_stream_wrapper' => [
'file' => __DIR__ . '/../examples/gridfs_stream_wrapper.php',
'expectedOutput' => $expectedOutput,
];

Expand Down Expand Up @@ -243,7 +265,7 @@ public function testAtlasSearch(): void

OUTPUT;

$this->assertExampleOutput(__DIR__ . '/../examples/atlas-search.php', $expectedOutput);
$this->assertExampleOutput(__DIR__ . '/../examples/atlas_search.php', $expectedOutput);
}

public function testChangeStream(): void
Expand Down