Question

i was getting in a question when i got this scenario:

I have to make a history log about what the user does and of course the user can do a lots different action.

i thought two different 2 way for make it i just need someone that can help me to follow the right way.

First way:

Create 2 different tables

  • History_user
  • History_type

History_user table

id | user_id | history_type (int)
 1      1             1
 1      3             2

History_type

id | name_action (string)
 1   The user has posted on the wall
 2   The user has change his profile picture

and then just join on the query with History_user.history_type = History_type.id

Second way:

is create the History_user table and an helper example called Converter.

<?php

class Converter {

  function history($type_history) {
        switch($type_history) {
           case 1:
            $human_history = "The user has posted on the wall";
           break;

           case 2:
             $human_history = "The user has change his profile picture";
           break;
        }

        return $human_history;
  }

}

$converter = new Converter();
$converter->history(1);

I was looking for the better way for do that, in terms of performance and maintainability. Thank you.

Was it helpful?

Solution

Both helper and History_type table are necessary for information representation. In terms of performance it doesn't really matter, because you will insert only in one table on user action. If you need to represent data, you will need just one more query to get descriptions of actions (without joins, ofc, if you want some performance). So 2 tables way is more flexible and extendable.

You still could do that helper function which lets say will have static cache variable - array of id => name of actions, which will be lazy loaded on history() function like this:

class Converter {
    protected static $_cache;

    protected static function _loadCache() {
        if (null !== self::$_cache) {
            return;
        }
        self::$_cache = array();
        $query = "SELECT * FROM `History_type`";
        $res = mysql_query($query);
        while ($row = mysql_fetch_assoc($res)) {
            self::$_cache[(int) $row['id']] = $row['action'];
        }
    }

    public static function history($id) {
        self::_loadCache();
        return isset(self::$_cache[$id]) ? self::$_cache[$id] : 'Undefined action';
    }
}

Converter::history(1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top