Custom data stream handling

As you have seen, PHP allows you to use fopen() to open network connections as well as files, and internally this is because PHP thinks of all data sources as "streams" so the functionality is the same to the end-user. What this means is that we can create our own stream handlers to handle new protocols and have them fit in automatically with functions like fopen() and file_get_contents() - this is a fast and easy route to truly advanced functionality.

To give you an idea of how streams can be used, we will be looking at two stream handlers: one that reads a file and automatically translates it to Morse code, and another that communicates with the "Amazing ROT13 Machine" we created earlier. Both of these can be done without streams, but doing it this way gives the end user more flexibility and, to be blunt, it is the easiest way to learn streams!

Custom streams are created using a class with a set of predefined functions. As there are many operations that can be performed on streams, there are equally many predefined functions to implement. However - thankfully - you only need implement the ones you intend to use. Of course, if you intend on distributing your stream wrappers, it is best you implement all the handlers as you just cannot tell what other users will do with the stream.

 

Next chapter: The Morse code stream >>

Previous chapter: Debugging Curl

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar