Using OOP styles for Drupal 7: callbacks

Drupal 7

Drupal 7 was created mainly with a procedural style but OOP styles can be used in many parts of it.

For example, there're many callbacks used in the Drupal 7 system. Originally they're expected being functions but some callbacks can be replaced to methods. Here are some examples.

Batch callbacks.

We can use methods for batch callbacks. Because the callback is stored in the database with a serialized manner and invoked with call_user_func_array().

function _batch_process() {
  // ...

  call_user_func_array($function, array_merge($args, array(&$batch_context)));
}

Cron queue tasks.

Cron queue task callbacks can be implemented with methods. Since they're invoked with call_user_func().

function drupal_cron_run() {
  // ...

  call_user_func($callback, $item->data);
}

On the other hand, for example, page callbacks in hook_menu() and action callbacks which live in hook_action_info() cannot be implemented with methods.

The reason why a page callback in hook_menu() cannot be defined with a method is that it must be a string when stored in the database. And the reason for an action callback is that it's checked with function_exists() and invoked with a $funtion() style. function_exists() returns false for methods and methods cannot be invoked with the $function() style.

function actions_do($action_ids, $object = NULL, $context = NULL, $a1 = NULL, $a2 = NULL) {

  // ...

  if (function_exists($function)) {
    $context = array_merge($context, $params);
    $actions_result[$action_id] = $function($object, $context, $a1, $a2);
  }

The conditions we can define a callback with a method are as follows.

This looks a trivial point at a glance but is quite effective for code maintainability if we do this properly :)


アバター
後藤隼人 ( ごとうはやと )

Python や PHP を使ってソフトウェア開発やウェブ制作をしています。詳しくはこちら