gotohayato.com

moon indicating dark mode
sun indicating light mode

Using OOP styles for Drupal 7: callbacks

2017/02/22Drupal 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().

<?php
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().

<?php
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.

  • A serialization happens when the callback is stored in the database. Otherwise, it must be a string (That is, it must be a function).
  • It’s invoked with call_user_func() or call_user_func_array(). The $function() style cannot be used for methods. And if function_exists() check is used for callbacks, methods cannot be used. FYI, The previous post explains why the methods cannot be called with the $function() style.

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

関連記事


後藤隼人
個人事業でウェブ開発やマーケティングをしています。
GitHub