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.

Working with Files and Images<br />

The third argument is a bitmask of options defined by PHP. The one we're<br />

dealing with here is STREAM_REPORT_ERRORS, which indicates whether or not<br />

PHP errors should be suppressed (for instance if a file is not found). The second is<br />

STREAM_USE_PATH, which indicates whether PHP's include path should be checked<br />

if a file is not found. This is not relevant to us, so we ignore it. If a file is found on<br />

the include path, then the fourth argument $opened_url should be set with the<br />

file's real path.<br />

Looking at the rest of the code for stream_open(), we can see how this<br />

comes together:<br />

$this->uri = $uri;<br />

$url = $this->getExternalUrl();<br />

We save our URI into a protected property, and then call getExternalURL() to<br />

translate it into an actual Twitpic URL that we can grab a photo from. We can then<br />

fopen() this URL and set our internal handle.<br />

if ($options && STREAM_REPORT_ERRORS) {<br />

$this->handle = fopen($url, $mode);<br />

}<br />

else {<br />

$this->handle = @fopen($url, $mode);<br />

}<br />

If STREAM_REPORT_ERRORS is not set, we suppress fopen() errors by prepending @,<br />

which indicates to PHP that errors should not be reported. It is always good coding<br />

practice to properly handle the options available to your stream functions if they are<br />

applicable to your user case.<br />

In addition to creating an implementation of <strong>Drupal</strong>StreamWrapperInterface,<br />

modules that define their own stream wrappers must register them with <strong>Drupal</strong>'s<br />

stream wrapper registry by implementing hook_stream_wrappers(). This hook<br />

returns an associative array defining some information about our stream wrapper,<br />

as shown in the following code:<br />

/**<br />

* Implement hook_stream_wrappers().<br />

*/<br />

function twitpic_stream_wrappers() {{<br />

return array(<br />

'twitpic' => array(<br />

'name' => 'Twitpic photos',<br />

'class' => 'TwitpicStreamWrapper',<br />

'description' => t('Photos from the Twitpic hosting service.')<br />

[ 324 ]

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

Saved successfully!

Ooh no, something went wrong!