The next four directives each provide module information to Drupal.

The name directive provides a human-readable display name for the module. In the last chapter, we briefly discussed the Drupal module installation and configuration interface. The names of the modules we saw there were extracted from the name directive in their corresponding .info tiles. Here's an example:

T re - optional Enabled Name

Version Description

Aggregator S.0-rc3

Aggregates syndicated content (RSS, RDF, and Atom feeds). [Code



Enables keeping easily and 6 0 rc3 regularly updated user web pages or blogs, [Code


In this above screenshot, the names Aggregator and Blog are taken from the values of the name directives in these modules' .info files.

While making the module's proper name short and concise is good (as we did when naming the module directory goodreads above), the display name should be helpful to the user. That usually means that it should be a little longer, and a little more descriptive.

However, there is no need to jam all of the module information into the name directive. The description directive is a good place for providing a sentence or two describing the module's function and capabilities.

The third directive is the directive.

The core and php directives are new in Drupal 6.


This directive specifies what version of Drupal is required for this module to function properly. Our value, 6.x, indicates that this module will run on Drupal 6 (including its minor revisions). In many cases, the Drupal packager will be able to automatically set this (correctly). But Drupal developers are suggesting that this directive be set manually for those who work from CVS.

Finally, the php directive makes it possible to specify a minimum version number requirement for PHP. PHP 5, for example, has many features that are missing in PHP 4 (and the modules in this book make use of such features). For that reason, we explicitly note that our modules require at least PHP version 5.1.

That's all there is to our first module .info file. In later chapters, we will see some other possible directives. But what we have here is sufficient for our Goodreads module.

Now, we are ready to write some PHP code.

A Basic .module File

As mentioned in the first chapter, there are two files that every module must have (though many modules have more). The first, the .info file, we examined above. The second file is the .module (dot-module) file, which is a PHP script file. This file typically implements a handful of hook functions that Drupal will call at predetermined times during a request.

I r^STX For an introduction to hooks and hook implementations, see the I

I previous chapter. I

Here, we will create a .module file that will display a small formatted section of information. Later in this chapter, we will configure Drupal to display this information to site visitors.

Our Goal: A Block Hook

For our very first module, we will implement the hook_block() function. In Drupal parlance, a block is a chunk of auxiliary information that is displayed on a page alongside the main page content. Sounds confusing? An example might help.

Think of your favorite news website. On a typical article page, the text of the article is displayed in the middle of the page. But on the left and right sides of the page and perhaps at the top and bottom as well, there are other bits of information: a site menu, a list of links to related articles, links to comments or forums about this article, etc. In Drupal, these extra pieces are treated as blocks.

The hook_block() function isn't just for displaying block contents, though. In fact, this function is responsible for displaying the block and providing all the administration and auxiliary functions related to this block. Don't worry... we'll start out simply and build up from there.

Starting the .module

As was mentioned in the last chapter, Drupal follows rigorous coding and documentation standards ( In this book, we will do our best to follow these standards. So as we start out our module, the first thing we are going to do is provide some API documentation.

Just as with the .info file, the .module file should be named after the module. Following is the beginning of our goodreads.module file:

* Module for fetching data from

* This module provides block content retrieved from a

* bookshelf.

* @see */

The .module file is just a standard PHP file. So the first line is the opening of the PHP processing instruction: <?php. Throughout this book you may notice something. While all of our PHP libraries begin with the <?php opening, none of them end with the closing ?> characters.

This is intentional, in fact, it is not just intentional, but conventional for Drupal. As much as it might offend your well-formed markup language sensibilities, it is good coding practice to omit the closing characters for a library.

Why? Because it avoids printing whitespace characters in the script's output, and that can be very important in some cases. For example, if whitespace characters are output before HTTP headers are sent, the client will see ugly error messages at the top of the page.

After the PHP tag is the keyword for the version control system:

When the module is checked into the Drupal CVS, information about the current revision is placed here.

The third part of this example is the API documentation. API documentation is contained in a special comment block, which begins /** and ends with a */. Everything between these is treated as documentation. Special extraction programs like Doxygen can pull out this information and create user-friendly programming information.

The Drupal API reference is generated from the API comments located in Drupal's source code. The program, Doxygen, (http://www.stack. I

nl/~dimitri/doxygen/) is used to generate the API documents from I the comments in the code.

The majority of the content in these documentation blocks (docblocks, for short) is simply text. But there are a few additions to the text.

First, there are special identifiers that provide the documentation generating program with additional information. These are typically prefixed with an @ sign.

* Module for fetching data from

* This module provides block content retrieved from a

* bookshelf.

* @see */

In the above example, there are two such identifiers. The @file identifier tells the documentation processor that this comment describes the entire file, not a particular function or variable inside the file. The first comment in every Drupal PHP file should, by convention, be a file-level comment.

The other identifier in the above example is the @see keyword. This instructs the documentation processor to attempt to link this file to some other piece of information. In this case, that piece of information is a URL. Functions, constants, and variables can also be referents of a @see identifier. In these cases, the documentation processor will link this docblock to the API information for that function, constant, or variable.

As we work through the modules in this book, we will add such documentation blocks to our code, and in the process we will encounter other features of docblocks.

With these formalities out of the way, we're ready to start coding our module.

The hook_block() Implementation

Our module will display information inside a Drupal block. To do this, we need to implement the hook_block() function.

Remember, what we are doing here is providing a function that Drupal will call. When Drupal calls a hook_block() function, Drupal passes it as many as three parameters:

The $op parameter will contain information about the type of operation Drupal expects the module to perform. This single hook implementation is expected to be able to perform a variety of different operations. Is the module to output basic information about itself? Or display the block? Or provide some administration information? The value of $op will determine this.

$op can have the following four possible values:

• list: This is passed when the module should provide information about itself. For example, when the list of modules is displayed in the module administration screen, the $op parameter is set to list.

• view: This value is passed in $op when Drupal expects the block hook to provide content for displaying to the user.

• configure: This value is passed when Drupal expects an administration form used to configure the block. We will look at this later.

• save: This value is passed when configuration information from the form data generated by configure needs to be saved.

The $delta parameter is set during a particular operation. When $op is set to the string view, which is the operation for displaying the block, then the $delta will also be set. $delta contains extra information about what content should be displayed. We will not use it in our first example, but we will use it later in the book. Take a look at Chapter 4 for another example of a hook_block() implementation.

Using deltas, you can define a single hook_block() function that can display several different blocks. For example, we might define , two deltas—one that displays our Goodreads bookshelf, and the other C^ that displays information about our Goodreads account. Which one is displayed will depend on which $delta value is passed into the goodreads_block() function. Other modules in this book will make use of deltas.

Finally, the $edit parameter is used during configuration (when the save operation is called). Since we are not implementing that operation in our first module, we will not use this parameter.

[ Drupal is meticulously documented, and the API documents are available T

online at More information about hook_ I

block() parameters is available at this URL: http://api.drupal. I

org/api/function/hook_block/6. J

All hook methods should follow the module naming convention: <module name>_

<hook name>. So our goodreads block hook will be named goodreads_block(). /**

* Implementation of hook_block() */

function goodreads_block($op='list', $delta=0, $edit=array()) {

$blocks[0]['info'] = t('Goodreads Bookshelf'); return $blocks;

$blocks['subject'] = t('On the Bookshelf'); $blocks['content'] = t('Temporary content'); return $blocks;

Following Drupal conventions, we precede the function with a documentation block. For hooks, it is customary for the documentation therein to indicate which hook it is implementing.

Next is our function signature: function goodreads_block($op='list', $delta=0, $edit=array()). The $op, $delta, and $edit parameters are all explained above. Each parameter is initialized to a default value. Here, we follow the customary defaults, but you can define them otherwise if you prefer.

As I mentioned earlier the $op parameter might be set to one of several different values.

What we do in this function is largely determined by which of those four values is set in the $op flag. For that reason, the first thing we do in this function is use a switch statement to find out which operation to execute.

Each case in the switch statement handles one of the different operations. For now, we don't have any administration configuration to perform, so there are no cases to handle either configure or save operations. We just need to handle the list and view operations. Let's look at each.

$blocks[0]['info'] = t('Goodreads Bookshelf'); return $blocks;

When Drupal calls this hook with $op set to 'list', then this module will return a two-dimensional array that looks as follows:

'info' => 'Goodreads Bookshelf'

Each element in this array is a block descriptor, which provides information about what this block implementation does. There should be one entry here for every $delta value that this function recognizes. Our block will only return one value (we don't make use of deltas), so there is only one entry in the block descriptor array.

A block descriptor can contain several different fields in the associative array. One is required: the 'info' field that we have set above. But we could also provide information on caching, default weighting and placement, and so on.

Drupal uses the 'info' field to display an item in the module management list, which we will see in the Installing a Module section of this chapter.


For detailed information on this and other aspects of the hook_block() \ hook, see the API documentation: function/hook_block/6

The t() Function

In this example, there is one more thing worthy of mention. We use the function t(). This is the translation function. It is used to provide multi-language support and also provide a standard method of string substitution. When t() is called, Drupal will check to see if the user's preferred language is other than the default (US English). If the user prefers another language, and that language is supported, then Drupal will attempt to translate the string into the user's preferred language.

Whenever we present hard-coded text to a user, we will use the t() function to make sure that multi-language support is maintained.

In simple cases, the t () function takes just a string containing a message. In this case, the entire string will be translated. But sometimes, extra data needs to be passed into the string function. For example, we may want to add a URL into a string dynamically:

'Trying to access !url.'

In this case, we want t() to translate the string, but to substitute a URL in place of the !url placeholder. To do this, we would call t() with the following parameters:

t('Trying to access !url.', array('!url,=>,'));

In this example, t() has two arguments: the string to translate, and an associative array where the key is the placeholder name and the value is the value to be substituted. Running the above when the locale is set to English will result in a string as follows:

Trying to access There are three different kinds of placeholder. We have seen one above.

• !: Placeholders that begin with the exclamation point (!) are substituted into the string exactly as is.

Sometimes it is desirable to do some escaping of the variables before substituting them into the string. The other two placeholder markers indicate that extra escaping is necessary.

• @: Placeholders that begin with an @ sign will be escaped using the check_plain() function. This will, for example, convert HTML tags to escaped entities. t('Italics tag: @tag', array( '@tag', '<i>')) will produce the string 'Italics tag: &lt;i&gt;'.

For multi-language support, you will need to enable the Content translation module.

• %: Placeholders that begin with the percent sign (%) are not only escaped, like those that start with the @, but are also themed. (We will look at theming in the next chapter.) Usually, the result of this theming is that the output value is placed in italics. So t('Replacing %value.', array('%value=>'test') will result in something like 'Replacing <em>test</em>'. The <em></em> tags are added by the translation function.

Don't trust user-entered data

It is always better to err on the side of caution. Do not trust data from external sources (like users or remote sites). When it comes to the t() function, this means you should generally not use placeholders beginning with ! if the source of the string to be substituted is outside of your control. (For example, it is inadvisable to do this: t('Hello !user', array('!user' => $_GET['username']) . Using @user or %user is safer.

We will use the t() function throughout this book. For now, though, let's continue looking at the hook_block() function we have created.

A view Operation

Now let's turn to the view case. This second case in our switch statement looks as follows:

$blocks['subject'] = t('On the Bookshelf'); $blocks['content'] = t('Temporary content'); return $blocks;

The view operation should return one block of content for displaying to the end user. This block of content must have two parts stored as name/value pairs in an associative array: a subject and a content item.

The subject is the title of the block, and the content is main content of the block. The value of the subject entry will be used as a title for the block, while the content will be placed into the block's content.

Again, we used the translation function, t(), to translate the title and content of this block.

While it is not terribly exciting yet, our module is ready to test. The next thing to do is install it.

Installing a Module

We have a working module. Now we need to install it. This is typically done in three steps:

1. Copying the module to the correct location

2. Enabling the module

3. Configuring Drupal to display the module's content

Some of the contributed modules for Drupal require additional setup T

steps. Such steps are documented by the module's authors. In Chapter 4, I we will create a module that requires a few additional steps before the module is useful.

We will walk through each of these three steps.

Step 1: Copying the Module

Modules in Drupal are stored in one of the three places under Drupal's root directory:

• modules/: This is the directory for core modules. Only modules supplied as part of the Drupal distribution should be stored here. None of our modules will ever be located here.

• sites/all/modules/: This is the directory for modules that should be available to all of the sites hosted on this Drupal installation. Usually, this is where you want to put your module.

• sites/<site name>/modules: Drupal can host multiple sites. Each site has a directory inside the sites/ folder. For example, the default site is located in sites/default/. If you want to install site-specific modules on an instance of Drupal that runs multiple sites, the modules should go into the sites/ <site name>/modules/ directory, where <site name> should be replaced by the correct site name.

In this book, we will be storing our modules under the sites/all/ modules/ directory.

However, this directory is not created by default, so we will need to create it by hand.

On my Linux server, Drupal is installed in /var/www/drupal/. (Yours may be somewhere else.) All of the file system paths will be relative to this directory. We will add the appropriate subdirectory inside the sites/all/ directory:

In this example, we change into the appropriate directory, create the new modules/ directory.

By default, the permissions on the directory should be set to allow the web-server user (such as www-data) access to the files in the module. However, on some systems you may have to set these yourselves.

0 0

Post a comment