Archive: September 2007

Drupal Role

September 10, 2007

Drupal 4.2.0 was the first CMS I ever installed, back in 2003. A few weeks later it became the first CMS I botched an upgrade to, at which point I moved on to other pastures.

That was that until last week, when John demanded help with a custom module for his mountaineering club site, to enable users to enter unique codes in their profile area and have their membership “upgraded” to a new role. I gather the point is to pass out the codes in meatspace when members join or pay their dues — it’s a clever idea.

A day or three later and the result was this module.

Most of my experience developing plugins for other people’s PHP comes from WordPress, so it was interesting to use such a dramatically different API. WordPress requires explicit registration of hook functions, e.g.

add_action("edit_post", "my_edit_post_action");

But Drupal uses magic function names. If you have a module called “mymodule“, any function called mymodule_init will be automatically hooked into hook_init.

It’s an elegant solution, though I favour the Pythonic “explicit is better than implicit” philosophy too much to be comfortable with it.

One of the best (and worst) things about the whole experience was the Forms API. Instead of writing HTML, you just write some code like this:

function mymodule_form() {
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#description' => t('What are you called?')
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Yield!'),
    );
    return $form;
}

Hook the function in at the appropriate place, and Drupal renders it, themed prettily, with anti-CSRF nonces already handled. More magic functions, hooked in as mymodule_form_validate() and mymodule_form_submit(), can be used for validation and form submission actions respectively.

As always, the downside of a leaky abstraction is that customizations not provided for in the API are much harder than they should be, but I expect that the vast majority of modules never have any problems.

Drupal has lots of other niceties missing from WordPress too, like the watchdog logging system and documentation that doesn’t suck. I have issues with it as a user — the learning curve for administration is comparatively steep — but it’s flexible, powerful, and easy to extend. As a developer I’m extremely impressed.

This page contains the archive of articles posted to rephrase.net during September 2007.