老葛的Drupal培训班 Think in Drupal
为了存储登录信息,我们需要使用一个.install文件来创建数据库表,所以我们创建了sites/all/modules/custom/loginhistory.install文件。
列表 6-4. loginhistory.install
<?php
// $Id$
/**
* Implementation of hook_install().
*/
function loginhistory_install() {
// Create tables.
drupal_install_schema('loginhistory');
}
/**
* Implementation of hook_uninstall().
*/
function loginhistory_uninstall() {
// Remove tables.
drupal_uninstall_schema('loginhistory');
}
/**
* Implementation of hook_schema().
*/
function loginhistory_schema() {
$schema['login_history'] = array(
'description' => t('Stores information about user logins.'),
'fields' => array(
'uid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => t('The {user}.uid of the user logging in.'),
),
'login' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => t('Unix timestamp denoting time of login.'),
),
),
'index' => array('uid'),
);
return $schema;
}
列表 6-5. loginhistory.module
<?php
// $Id$
/**
* @file
* Keeps track of user logins.
*/
/**
* Implementation of hook_user().
*/
function loginhistory_user($op, &$edit, &$account, $category = NULL) {
switch($op) {
// Successful login.
case 'login':
// Record timestamp in database.
db_query("INSERT INTO {login_history} (uid, login) VALUES (%d, %d)",$account->uid, $account->login);
break;
// $user object has been created and is given to us as $account parameter.
case 'load':
// Add the number of times user has logged in.
$account->loginhistory_count = db_result(db_query("SELECT COUNT(login) AS count FROM {login_history} WHERE uid = %d", $account->uid));
break;
// 'My account' page is being created.
case 'view':
// Add a field displaying number of logins.
$account->content['summary']['login_history'] = array(
'#type' => 'user_profile_item',
'#title' => t('Number of Logins'),
'#value' => $account->loginhistory_count,
'#attributes' => array('class' => 'login-history'),
'#weight' => 10,
);
break;
}
}
在安装了这个模块以后,对于每次成功的用户登录,都将调用user钩子的login操作,在这个钩子里面,模块将向数据库表login_history插入一条记录。在加载$user对象时,将会调用用户加载钩子,此时模块将把用户的当前登录次数添加$user->loginhistory_count中。当用户查看“我的帐号”页面时,登录次数将显示出来,如图6-5所示。
图6-5 追踪用户的登录历史
注意 当你在你的模块中为对象$user或$node添加属性时,在属性名前面最好加上前缀,以避免命名空间的冲突。这就是为什么这里使用$account->loginhistory_count来代替$account->count的原因。
尽管在“我的帐号”页面,我们显示了我们添加到$user上的额外信息,记住由于$user对象是全局变量,所以其它模块也能访问它。我们留给读者一个非常有用的联系,为了安全起见,来修改前面的模块,在左(或右)边栏的区块中提供一个格式美观的历史登录列表(“喂!我今天上午3:00没有登录”)。