官术网_书友最值得收藏!

Using tokens

To quickly demonstrate how we can use tokens, let's include in our hello_world_log mails some information about the current user at the time the email is being sent out. This will naturally coincide with the user that is signed in at the time the error is being logged.

For this, we will need to alter our hook_mail() implementation. In there, we will ask the current_user service for the AccountProxy of the current user, add another string to our mail body and, of course, replace a token:

/**
* Implements hook_mail().
*/
function hello_world_mail($key, &$message, $params) {
switch ($key) {
case 'hello_world_log':
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = t('There is an error on your website');
$message['body'][] = $params['message'];
$user_message = 'The user that was logged in: [current-user:name].';
$message['body'][] = \Drupal::token()->replace($user_message, ['current-user' => \Drupal::currentUser()]);

break;
}
}

As you can see, we are adding a new "paragraph" to our email. This is a simple string that informs us about the user that was logged in. However, in doing so, we use the token service (statically) to replace that piece of string with the token value. The replace() method of the service takes a string and optionally an array of data objects keyed by the type (group) of the tokens they should be used for.

The choice of token and type in this case is important. The User module defines the user and current-user types. The difference between the two, if you check inside user_tokens(), is that the latter simply delegates to the former after it loads a full user entity. We could, alternatively, have done that ourselves and then passed the user type, but why should we? If somebody has done that for us already, we should not have to do it again. And what we pass to the current-user token type as a data object to be used in the replacement process is the AccountProxy (current user session).

So, that's it. Now, the email message will get an extra line that contains the dynamically generated username of the currently logged-in user at the time the error happened. Under the hood, the token service scans the string, extracts the token, and calls all hook_tokens() implementations. The User module is the one that can return the replacement for this token based on the User object it receives.

主站蜘蛛池模板: 大丰市| 隆化县| 蓬安县| 浮山县| 扶沟县| 嘉黎县| 若羌县| 新绛县| 冀州市| 台东市| 花莲县| 大邑县| 常宁市| 句容市| 松江区| 赤水市| 社旗县| 康马县| 大港区| 沅陵县| 皋兰县| 武邑县| 南陵县| 枝江市| 阳曲县| 安陆市| 镇坪县| 萨嘎县| 延边| 阿尔山市| 广汉市| 大邑县| 克山县| 玉屏| 新平| 孝昌县| 吴川市| 宁安市| 黎城县| 拉萨市| 米脂县|