Telling Drupal who can use your module

Last modified: June 10, 2009 - 15:08

Main topic described: Permissions
Drupal hook described: hook_perm

The next function to write is the permissions function, implementing Drupal's hook_perm(). This is where you will define the names of the permissions of your module -- it doesn't grant permission or define what the permissions mean, it just specifies what permissions are available for this module. As with the help hook from the previous tutorial page, we implement hook_perm() by creating a function called onthisdate_perm() in the onthisdate.module file. This function just needs to return a list of the permission names this module will use; once you have defined permissions in the hook_perm() implementation in a module, an administrator can define which roles have those permissions on the Administer » User management » Permissions page. Here is the function for our example module:

<?php
/**
* Valid permissions for this module
* @return array An array of valid permissions for the onthisdate module
*/
function onthisdate_perm() {
  return array(
'access onthisdate content');
}
// function onthisdate_perm()
?>

(Note for beginners: the opening <?php will only appear once in your module file, at the beginning, and the closing ?> will not appear in your file at all.)

If you are going to write a module that needs to have finer control over the permissions, you can expand this permission set. For example:

<?php
return array('access onthisdate content', 'administer onthisdate');
?>

For this tutorial, start with just the one permission. We'll later expand to using additional permissions.

Your permission strings are arbitrary, but each must be unique among all installed modules. Otherwise, one occurrence of the name will take the permissions of the other. For that reason, the permission strings should each usually contain your module name, since this helps avoid name space conflicts with other modules. The suggested naming convention for permissions is "action_verb modulename". Use the following example as a template for any module you may be developing:

<?php
function newmodule_perm() {

return array(
'access newmodule', 'create newmodule', 'administer newmodule');

}
// function newmodule_perm
?>

See Also

 
 

Drupal is a registered trademark of Dries Buytaert.