18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 11<br />

A read-only stream wrapper like ours needs to perform two main functions. First, it<br />

needs to translate a URI like twitpic://y6vvv/thumb to a URL or path that can be<br />

opened and read. Second, it needs to be able to open a file handle to this resource so<br />

that developers can get the necessary data.<br />

To manage the first requirement, we have implemented getExternalURL(). Any<br />

class implementing <strong>Drupal</strong>StreamWrapperInterface is required to override this<br />

function with their own implementation. This code is pretty straightforward; we just<br />

parse the object's URI, set some appropriate defaults, and return an appropriately<br />

structured Twitpic API URL:<br />

function getExternalUrl() {<br />

// Get image_id and size from the URI into an array.<br />

$target = file_uri_target($this->uri);<br />

$options = array_combine(<br />

array('image_id', 'size'),<br />

explode('/', $target)<br />

);<br />

Note the use of file_uri_target() to retrieve the target information from the URI.<br />

This is a helper function provided by the <strong>Drupal</strong> File API to make it easier to parse<br />

stream wrapper URIs. You can also call file_uri_scheme() to retrieve the scheme<br />

from a URI.<br />

The stream_open() function is similarly straightforward. This will get called<br />

when a developer tries to open a resource handled by our stream wrapper using<br />

PHP functions like fopen() or file_get_contents().This function takes four<br />

arguments, and needs to return FALSE or a handle to our resource.<br />

The first argument is our wrapper's URI. The second argument, $mode, indicates<br />

whether the stream should be opened for reading and/or writing, as well as<br />

other flags. Any mode can have b appended to it, to indicate that the file should be<br />

opened in binary mode. (So where r indicates read-only, rb indicates read-only in<br />

binary mode.)<br />

$allowed_modes = array('r', 'rb');<br />

if (!in_array($mode, $allowed_modes)) {<br />

return FALSE;<br />

}<br />

We are implementing a read-only scheme, so if we get any mode other than r or rb<br />

we return FALSE.<br />

[ 323 ]

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

Saved successfully!

Ooh no, something went wrong!