|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * This example demonstrates how to use streams with GridFS. |
| 5 | + */ |
| 6 | + |
| 7 | +declare(strict_types=1); |
| 8 | + |
| 9 | +namespace MongoDB\Examples; |
| 10 | + |
| 11 | +use MongoDB\Client; |
| 12 | +use MongoDB\Driver\Monitoring\CommandFailedEvent; |
| 13 | +use MongoDB\Driver\Monitoring\CommandStartedEvent; |
| 14 | +use MongoDB\Driver\Monitoring\CommandSubscriber; |
| 15 | +use MongoDB\Driver\Monitoring\CommandSucceededEvent; |
| 16 | + |
| 17 | +use function fclose; |
| 18 | +use function feof; |
| 19 | +use function fread; |
| 20 | +use function fwrite; |
| 21 | +use function getenv; |
| 22 | +use function range; |
| 23 | +use function var_dump; |
| 24 | + |
| 25 | +use const PHP_EOL; |
| 26 | + |
| 27 | +require __DIR__ . '/../vendor/autoload.php'; |
| 28 | + |
| 29 | +$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/'); |
| 30 | +$client->getManager()->addSubscriber(new class implements CommandSubscriber { |
| 31 | + public function commandStarted(CommandStartedEvent $event): void |
| 32 | + { |
| 33 | + var_dump($event->getCommand()); |
| 34 | + //var_dump(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)); |
| 35 | + } |
| 36 | + |
| 37 | + public function commandSucceeded(CommandSucceededEvent $event): void |
| 38 | + { |
| 39 | + } |
| 40 | + |
| 41 | + public function commandFailed(CommandFailedEvent $event): void |
| 42 | + { |
| 43 | + } |
| 44 | +}); |
| 45 | + |
| 46 | + |
| 47 | +$gridfs = $client->selectDatabase('test')->selectGridFSBucket(); |
| 48 | + |
| 49 | +// Open a stream for writing, similar to fopen with mode 'w' |
| 50 | +$stream = $gridfs->openUploadStream('hello.txt'); |
| 51 | + |
| 52 | +foreach (range(0, 1_000) as $i) { |
| 53 | + fwrite($stream, 'Hello world! ' . $i . PHP_EOL); |
| 54 | +} |
| 55 | + |
| 56 | +// Last data are flushed to the server when the stream is closed |
| 57 | +fclose($stream); |
| 58 | + |
| 59 | +// Open a stream for reading, similar to fopen with mode 'r' |
| 60 | +$stream = $gridfs->openDownloadStreamByName('hello.txt'); |
| 61 | + |
| 62 | +while (! feof($stream)) { |
| 63 | + $data = fread($stream, 1024); |
| 64 | + echo "\n\nRead next " . strlen($data) . " bytes\n"; |
| 65 | + echo $data; |
| 66 | +} |
0 commit comments