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.

Chapter 4<br />

In Chapter 5, Building an Admin Interface, you'll learn how to build administration<br />

forms that could make our single_blog module configurable, but in this chapter we<br />

simply created a few PHP constants that define the node type to use for blog entries<br />

and the list count for block.<br />

Next up, we provided a simple API for our module that allows any code to retrieve<br />

a list of blog nodes; we've called the function single_blog_list(). We're using<br />

<strong>Drupal</strong>'s Database API to query for the data. You can learn more about it from<br />

<strong>Drupal</strong>'s online documentation at http://drupal.org/node/310069. For now,<br />

you'll have to rely on DB API's relatively self-documenting method names. We<br />

selected the unique node ID, title, creation date and author (uid stands for user ID)<br />

fields of nodes that are of the SINGLE_BLOG_NODE_TYPE content type and that are<br />

published (status = 1). We only selected the $number latest nodes that have<br />

been created.<br />

Why did we create a single_blog_list() function instead of just putting that<br />

database query code inside hook_block_view()? Some <strong>Drupal</strong> developers get so<br />

caught up in hooking into <strong>Drupal</strong>'s APIs that they forget to write abstracted APIs for<br />

their own module's business logic. Don't make that same mistake. We could put the<br />

database query inside a <strong>Drupal</strong> hook, but that reduces the chance that other modules<br />

can integrate with your module in ways you could never anticipate. Remember, be<br />

lazy. If your module's API is good enough, some other developer will write the code<br />

to integrate your module with theirs.<br />

Now that we have our API function written, let's use it to build the block using<br />

<strong>Drupal</strong>'s Block API:<br />

/**<br />

* Implements hook_block_info().<br />

*/<br />

function single_blog_block_info() {<br />

$blocks = array();<br />

// The array key defines the $delta parameter used in all<br />

// other block hooks.<br />

$blocks['recent'] = array(<br />

// The name of the block on the blocks administration page.<br />

'info' => t('Recent blog posts'),<br />

);<br />

}<br />

return $blocks;<br />

/**<br />

* Implements hook_block_view().<br />

*<br />

[ 95 ]

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

Saved successfully!

Ooh no, something went wrong!