PSR-7 StreamInterface "fgets"

393 views
Skip to first unread message

Bradyn Poulsen

unread,
May 16, 2016, 7:22:47 PM5/16/16
to PHP Framework Interoperability Group
Hey everyone,

I've been utilizing PSR-7 pretty heavily in my projects to utilize dependency inversion. My latest project has been specifically utilizing the StreamInterface. Were there reasons why StreamInterface didn't include an `fgets` equivalent?

For example,

public function handleResource($resource)
{
   
while ($line = fgets($resource)) {
       
// do something with $line
   
}
}

public function handleStream(StreamInterface $stream)
{
   
while ($line = $stream->getLine()) {
       
// do something with $line
   
}
}


Woody Gilk

unread,
May 16, 2016, 9:00:54 PM5/16/16
to PHP Framework Interoperability Group
You can call detach() on the stream to get the actual stream resource and use it with fgets(). Just be aware that it will make the PSR-7 stream unusable.

Dracony

unread,
May 17, 2016, 5:01:46 AM5/17/16
to PHP Framework Interoperability Group
It's rather an unusual usecase to read the HTTP stream line by line, even large requests would probably be read using a buffer with some fixed size, but not from newline to newline

Bradyn Poulsen

unread,
May 17, 2016, 1:23:04 PM5/17/16
to PHP Framework Interoperability Group
+Dracony, ok. Then in the case of needing line by line, I would read in a chunk and then parse that by lines?

Dracony

unread,
May 18, 2016, 10:23:55 AM5/18/16
to PHP Framework Interoperability Group
Sure, it's pretty trivial

Andrew Carter

unread,
May 18, 2016, 10:36:45 AM5/18/16
to PHP Framework Interoperability Group
You can also detach the stream and do an fgets() on the resource that's returned. This will make the stream unusable and might cause you other problems (as the stream will not necessarily be attached to a resource).

Evert Pot

unread,
May 18, 2016, 12:09:40 PM5/18/16
to PHP Framework Interoperability Group


On Monday, May 16, 2016 at 9:00:54 PM UTC-4, Woody Gilk wrote:
You can call detach() on the stream to get the actual stream resource and use it with fgets(). Just be aware that it will make the PSR-7 stream unusable.

 There's actually no guarantee that that function returns a stream.

Evert

Andrew Carter

unread,
May 18, 2016, 12:13:39 PM5/18/16
to PHP Framework Interoperability Group
Read the next part of my response ;)

Evert Pot

unread,
May 18, 2016, 12:21:20 PM5/18/16
to PHP Framework Interoperability Group


On Wednesday, May 18, 2016 at 12:13:39 PM UTC-4, Andrew Carter wrote:
Read the next part of my response ;)

 Whoops. Sorry :(

Reply all
Reply to author
Forward
0 new messages