Skip to content

Instantly share code, notes, and snippets.

@harikt
Last active August 29, 2015 14:26
Show Gist options
  • Save harikt/1874dc04415e8a1a1500 to your computer and use it in GitHub Desktop.
Save harikt/1874dc04415e8a1a1500 to your computer and use it in GitHub Desktop.
PSR-7 Streams and usage of setting the file to be downloaded without explicitly making it to an implementation like zend-diactoros.

Hi,

I was looking a small piece of code

$file = new SplFileObject($path);
while (! $file->eof()) {
   echo $file->fgets();
}

What it is doing is wrap in a closure and read the content only when it is really used.

For a fully understanding of the piece of code, please have a look at https://github.com/friendsofaura/Aura.Asset_Bundle/blob/master/src/AssetResponder.php#L110-L115

I was trying to move it to make use of Psr-7 response and seems there is no other way to rely on the interface, but to use the implementors method or re-invent one again.

Is there a way to achieve this than what I am looking ?

// $response , a psr7 Response
// StreamInterface
$stream = $response->getBody();

The StreamInterface https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-7-http-message.md#34-psrhttpmessagestreaminterface have a method called write() which should be a string. In our case this a closure.

I wished if it would have a method called setFilePath or something and the implementors can read from and do what the above code was doing.

@harikt
Copy link
Author

harikt commented Aug 9, 2015

My understanding is you want to create your own Stream to do this. If there was a method to set the file we would have not reinvent it ? I am looking at https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-7-http-message-meta.md#what-if-i-just-want-to-return-a-file

@harikt
Copy link
Author

harikt commented Aug 9, 2015

Diactoros stream https://github.com/zendframework/zend-diactoros/blob/master/src/Stream.php#L36 and Slim stream https://github.com/slimphp/Slim/blob/3.x/Slim/Http/Stream.php#L82 itself have different implementation. Seems it would be nice if PSR-7 stream itself have defined a setFilePath method and when there is no contents in the body can try to open the file path and get the output. See copy stream example from @MWOP https://github.com/phly/psr7examples/blob/master/public/copy-stream.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment