From 5c6133ae679fae68590b9fa23f11c8065c71b39d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Tue, 21 Nov 2023 15:23:46 +0100 Subject: [PATCH] Add examples on gridfs --- examples/gridfs-stream.php | 66 ++++++++++++++++++++++++++++++++++++++ examples/gridfs-upload.php | 41 +++++++++++++++++++++++ 2 files changed, 107 insertions(+) create mode 100644 examples/gridfs-stream.php create mode 100644 examples/gridfs-upload.php diff --git a/examples/gridfs-stream.php b/examples/gridfs-stream.php new file mode 100644 index 000000000..5f4d90c1f --- /dev/null +++ b/examples/gridfs-stream.php @@ -0,0 +1,66 @@ +getManager()->addSubscriber(new class implements CommandSubscriber { + public function commandStarted(CommandStartedEvent $event): void + { + var_dump($event->getCommand()); + //var_dump(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)); + } + + public function commandSucceeded(CommandSucceededEvent $event): void + { + } + + public function commandFailed(CommandFailedEvent $event): void + { + } +}); + + +$gridfs = $client->selectDatabase('test')->selectGridFSBucket(); + +// Open a stream for writing, similar to fopen with mode 'w' +$stream = $gridfs->openUploadStream('hello.txt'); + +foreach (range(0, 1_000) as $i) { + fwrite($stream, 'Hello world! ' . $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 = $gridfs->openDownloadStreamByName('hello.txt'); + +while (! feof($stream)) { + $data = fread($stream, 1024); + echo "\n\nRead next " . strlen($data) . " bytes\n"; + echo $data; +} diff --git a/examples/gridfs-upload.php b/examples/gridfs-upload.php new file mode 100644 index 000000000..e2f74656e --- /dev/null +++ b/examples/gridfs-upload.php @@ -0,0 +1,41 @@ +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 a file +$id = $gridfs->uploadFromStream('hello.txt', $stream); +echo 'Inserted file with ID: ' . $id . PHP_EOL; + +// Download the file +$stream = $gridfs->openDownloadStreamByName('hello.txt'); +echo 'Downloaded file contents: ' . stream_get_contents($stream) . PHP_EOL; + +// Delete the file +$gridfs->delete($id);