Created
April 3, 2011 17:02
-
-
Save nickyleach/900565 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
include_once 'iredis.php'; | |
class ActivityFeed { | |
private $redis; | |
public function __construct(){ | |
$this->redis = new iRedis(); | |
} | |
// Adds an activity for a user | |
public function add($userID, $data, $time = null){ | |
if(!$time) $time = time(); | |
$key = $this->_key('User', $userID); | |
return $this->redis->zadd($key, $time, $data); | |
} | |
// Returns an array of the activity feed for userID | |
public function userActivity($userID, $num = null, $before = null, $after = null){ | |
$key = $this->_key('User', $userID); | |
$activity = $this->_activity($key, $num, $before, $after); | |
return $activity; | |
} | |
// Returns an array of the union of activity feeds for the supplied userIDs | |
// and stores it in a key for userID | |
public function usersActivity($userID, $userIDs, $num = null, $before = null, $after = null){ | |
$usersKey = $this->_key('Users', $userID); | |
$args = array(); | |
foreach($userIDs as $_userID){ | |
$args[] = $this->_key('User', $_userID); | |
} | |
// zunionstore expects parameters: destination numkeys key [key ...] | |
array_unshift($args, $usersKey, count($userIDs)); | |
call_user_func_array(array($this->redis, 'zunionstore'), $args); | |
$usersActivity = $this->_activity($usersKey, $num, $before, $after); | |
return $usersActivity; | |
} | |
// Helper method that returns an array of activity indexed by the activity time | |
private function _activity($key, $num = null, $before = null, $after = null){ | |
$_activity = $this->redis->zrevrangebyscore($key, ( $before ? $before : '+inf' ), ( $after ? $after : '-inf' ), 'WITHSCORES'); | |
$activity = array(); | |
foreach($_activity as $key => $val){ | |
// When 'WITHSCORES' is provided, zrevrangebyscore returns an array in the format: (activity1, score1, activity2, score2, ...) | |
if($key % 2 == 0){ | |
$activity[$_activity[$key + 1]] = $val; | |
} | |
} | |
if($num) $activity = array_slice($activity, 0, $num); | |
return $activity; | |
} | |
// Helper method that returns a namespaced key | |
private function _key($type, $id){ | |
return "AF:$type:$id"; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added a bugfix: $num wasn't being respected