创建.Install文件

在Drupal 7中,“.install”文件用于创建数据库表和字段,并插入数据。
'.install'文件也用于更新表结构和内容。
'.install'文件是具有不同扩展名的PHP文件。

将“.install”文件(mymodule.install)创建到模块的根目录中。
使用此文件,我们将在数据库中创建一个订户表以存储用户的数据。

使用hook_update_n()

hook_update_n函数用于在更新模块时添加,更新或者删除数据库表,字段或者内容。
例如,在我们要在订阅者表中添加新列的最新版本。

hook_update_n函数将是以下内容。

function mymodule_update_2() {
    $ret = array();
    db_add_field($ret, 'subscribers', 'country', array(
        'description' => 'Subscriber country.',
        'type' => 'varchar',
        'default' => '',
        'length' => 255,
        'not null' => TRUE,
    ));
    return $ret;
}

定义hook_schema()

'hook_schema()'保存一个数组结构,用于表示一个或者多个表及其相关键和索引。

为订阅者定义'hook_schema'表,并写下以下代码。

function mymodule_schema(){
    $schema['subscribers'] = array(
        'description' => 'The table for storing the subscriber data.',
        'fields' => array(
            'id' => array(
                'description' => 'The primary identifier for subscriber.',
                'type' => 'serial',
                'not null' => TRUE,
                'unsigned' => TRUE,
            ),
            'name' => array(
                'description' => 'Subscriber name.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
            ),
            'email' => array(
                'description' => 'Subscriber email.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
            ),
            'subscription_date' => array(
                'description' => 'Subscription date time(yyyy-mm-dd H:i:s).',
                'type' => 'varchar',
                'mysql_type' => 'DATETIME',
                'not null' => TRUE,
            ),
            'status' => array(
                'description' => 'Subscriber status(1=Unblock,0=Block).',
                'type' => 'int',
                'length' => 1,
                'not null' => TRUE,
                'default' => 1,
            ),
        ),
        'primary key' => array('id'),
    );
    return $schema;
}

在'hook_install()'之前调用'hook_schema()',并在'hook_uninstall()'后调用。
如果由'hook_schema()'声明的表,则在卸载模块时首先启用并删除模块时,将自动创建表。

Drupal自定义模块 - 在安装期间创建数据库表

我们将学习自定义Drupal模块的高级功能。

假设,模块需要数据库表来存储模块相关数据。
在本教程中,我们将讨论模块安装期间在数据库中创建表的过程。
模块需要“.install”文件,它可以帮助模块在卸载模块时首先启用并删除模块时创建所需的表。
此外,我们可以根据模块的更新版本更新数据库表。

日期:2020-06-02 22:18:57 来源:oir作者:oir