Drupal Batch API giúp chia nhỏ lại các processes trên webserver

Jun

18

Drupals internal batch API can be really helpful for handling large cumbersome processes on your web server. Rather than submitting a form and waiting for one of these processes to finish before reaching the next page, the batch API can be utilized to break the process down across multiple page loads. This not only cuts down on the server load, but will prevent the page from timing out. Progress bars will be displayed to the user while the process runs which will keep them informed of where they are at in the process.

In this example, I’ll explain how to do a simple assembly line-like process to generating page nodes in bulk, similar to Devel’s node generate function.

Youʼll need to start with a custom module. First, create a simple page with a form on it where you can specify the title of the pages, and how many you want to create. This is somewhat irrelevant but in order to show an example of how the batch API works we’ll need it.

function batch_demo_batch($title, $qty, &$context){
global $user;
/*
Set the number of nodes you want to create within a single iteration of the batch. This number
should be pretty low as it is the reason why we're creating the batch process in the first place.
*/
$limit = 10;
/*
Set the variables that need to persist throughout the batch process. These need to be set inside
the $context array because that's what persists throughout the process.
*/
if (!isset($context['sandbox']['progress'])) {
$context['sandbox']['progress'] = 0; $context['sandbox']['title'] = $title; $context['sandbox']['max'] = $qty;
}
// Create some new nodes based on current progress and the $limit per page load. It’s important that you get this right otherwise you can potentially get stuck in an infinite loop or the process won’t do what you want it to.
for($i = 0; $i < $limit; $i++){
if($context['sandbox']['progress'] < $context['sandbox']['max']){
$node = node_load();
$node->title = $context['sandbox']['title'].' #'.$context ['sandbox']['progress'];
$node->uid = $user->uid; $node->type = 'page';
node_save($node);
$context['sandbox']['progress']++; // Used to keep track of how many nodes we've already created.
$context['results'][] = check_plain($node->title); // Keep a running tab of all of the nodes created.
$context['message'] = "Created node " . $context ['sandbox']['progress'] . " of " . $context['sandbox']['max'];
}
}
// Check if the batch is finished
if ($context['sandbox']['progress'] < $context['sandbox'] ['max']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
}
}