18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Working with Files and Images<br />

Creating a stream wrapper<br />

In this example we are going to create a stream wrapper to retrieve photos from<br />

Twitpic, an image hosting service for Twitter users. Twitpic defines a REST API<br />

to retrieve photos from the URL http://twitpic.com/show//<br />

where size is either mini or thumb, and image-id is a unique identifier you can<br />

retrieve from a photo's URL, as seen in the following screenshot:<br />

The full Twitpic API is defined at http://twitpic.com/api.do<br />

So you can retrieve the thumbnail of this photo from the URL http://twitpic.<br />

com/show/thumb/7nyr2. This makes it very easy to refer to photos from Twitpic<br />

in your code. However, if this URL format should change, then you could end up<br />

with a lot of code to clean up. We can mitigate this by writing a stream wrapper<br />

that encapsulates this logic in one place. This stream wrapper will use the format<br />

twitpic:///.<br />

There are two things that we need to do to create a custom stream wrapper in<br />

<strong>Drupal</strong>. First, we need to create a custom class which implements our functionality,<br />

then we need to register the class using hook_stream_wrappers().<br />

PHP defines a set of functions that stream wrappers can implement, as listed at<br />

http://www.php.net/manual/en/class.streamwrapper.php. <strong>Drupal</strong> expanded<br />

on that list and created an interface called <strong>Drupal</strong>StreamWrapperInterface. Any<br />

stream wrapper class used in <strong>Drupal</strong> must implement this interface or else it will<br />

not register properly.<br />

[ 320 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!