• Services

User address book

In certain situations, you want users to be able to choose from a list of users, groups of other entities they have recently interacted with within their community. You are of course free to implement this in any way you see fit, but there is also a standard way that some of the default modules on the Includable platform use. This document describes retrieving and adding items to this personal "address book".

Abstract

Address book items are saved in user val key address_book. This user val contains an array of associative arrays, which contain the following fields:

Key Description
string type Can have any value, but most modules only support values user and group, where user indicates that the value key contains a user ID, and group indicates that the value key contains a group ID.
mixed value Usually integer value. The reference to the specific entity with the type specified by key type.
int community ID of the community in which this entity is added to the address book.
int time Timestamp this entry was added. Should be UNIX UTC (via time()).

Code samples

Retrieving items

// Retrieve address book (force cast to array so that this statement
// works even when the address book is empty)
$address_book = (array)$this->user->val('address_book');

// Optional: sort by time added to show most recent entries first
usort($address_book, function($entity1, $entity2) {
    return $entity1['time'] > $entity2['time'];
});

// Go over each entry
foreach($address_book as $entity) {
    $entity = (array)$entity;

    if($entity['community'] != $this->site->id){
        continue;
    }

    switch($entity['type']) {
        case 'user':
            // User entity
            $user = new User($entity['value']);
            // TODO: do something with `$user`
            break;
        case 'group':
            // User group entity
            $group = $this->db->select('communities_groups', ['id' => $entity['value']], 1)->row();
            // TODO: do something with `$group`
            break;
    }
}

Saving a new item

$user_to_save = new User(40);

$address_book = (array)$this->user->val('address_book');
$address_book[] = [
    'type' => 'user',
    'value' => $user_to_save->id,
    'community' => $this->site->id,
    'time' => time()
];

$this->user->val('address_book', $address_book);

Notes

  • Don't forget to check if these entities still exist. It might be that there's a reference to a user in the address book that might have been deleted or disabled.