You are here

检查上下文

将钩子和操作放在上下文中,这一点非常有用。我们举个例子,动作“发送电子邮件”就大量的利用了这一点。这个动作的类型为system,它可以被分配给许多不同的触发器。

 
    动作“发送电子邮件”在合成电子邮件期间,允许将特定的令牌替换掉。例如,你可能想在邮件的正文中包含一个节点的标题,或者想把节点的作者作为电子邮件的收件人。但是根据该动作分配给的触发器的不同,该收件人可能并不可用。例如,如果是在用户钩子中发送的电子邮件,由于没有节点可用,所以更谈不上让节点作者作为收件人了。modules/system/system.module中的动作“发送电子邮件”,它首先会花点时间来检查上下文从而判定有什么可用。下面,它将确保当前有一个节点,这样就可以利用节点相关的各种属性了:
 
/**
* Implementation of a configurable Drupal action. Sends an e-mail.
*/
function system_send_email_action($object, $context) {
    global $user;
    switch ($context['hook']) {
        case 'nodeapi':
            // Because this is not an action of type 'node' (it's an action
            // of type 'system') the node will not be passed as $object,
            // but it will still be available in $context.
            $node = $context['node'];
            break;
        case 'comment':
            // The comment hook provides nid, in $context.
            $comment = $context['comment'];
            $node = node_load($comment->nid);
        case 'user':
            // Because this is not an action of type 'user' the user
            // object is not passed as $object, but it will still be
            // available in $context.
            $account = $context['account'];
            if (isset($context['node'])) {
                $node = $context['node'];
            }
            elseif ($context['recipient'] == '%author') {
                // If we don't have a node, we don't have a node author.
                watchdog('error', 'Cannot use %author token in this context.');
                return;
            }
            break;
        default:
            // We are being called directly.
            $node = $object;
    } ...
 老葛的Drupal培训班 Think in Drupal

Drupal版本: