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 8<br />

The user_access() function is very effective, and it can be used in almost all cases.<br />

Since it only takes two parameters, it may not be appropriate for all access checks,<br />

and it can never check multiple permissions at once. Later, we will look at use cases<br />

where a more complex function is needed to check permissions.<br />

Using hook_permission()<br />

Now that you understand the basics of <strong>Drupal</strong>'s user access system, we can explore<br />

how modules can extend that system. First, a little history lesson.<br />

Until <strong>Drupal</strong> 7, hook_permission() was known as hook_perm(). The change was<br />

made for clarity in the code, as part of a general semantic cleanup of <strong>Drupal</strong> core.<br />

(I wrote the patch, in fact.) hook_permission() also includes a number of usability<br />

improvements, which altered the format of the function's return value. These<br />

changes are substantial enough for even experienced <strong>Drupal</strong> developers to explore<br />

each element of the new hook.<br />

The purpose of hook_permission() is to define and return an array that contains all<br />

the necessary information about your module's permissions. This includes the simple<br />

strings that can be passed to user_access(), plus a human-readable name for the<br />

permission and an optional description. Prior to <strong>Drupal</strong> 7, only the simple string<br />

was returned.<br />

The following is an example, taken from the core Search module:<br />

function search_permission() {<br />

return array(<br />

'administer search' => array(<br />

'title' => t('Administer search'),<br />

),<br />

'search content' => array(<br />

'title' => t('Use search'),<br />

),<br />

'use advanced search' => array(<br />

'title' => t('Use advanced search'),<br />

),<br />

);<br />

}<br />

The module declares three separate permissions in a manner typical to <strong>Drupal</strong><br />

modules. The first permission is for administrative configuration of the module.<br />

These sorts of permissions are rarely given to the "authenticated user" role and<br />

should never be given to anonymous users.<br />

[ 217 ]

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

Saved successfully!

Ooh no, something went wrong!