Rediska

Follow me on twitter…

Extending

Very useful practice - extend key objects and use them as your application models.

Example

<?php

class User extends Rediska_Key_Hash
{
    protected $_userId;
    public function __construct($userId)
    {
        $this->_userId = $userId;
        parent::__construct("users:$userId");
    }
}

class UserFriends extends Rediska_Key_Set
{
    protected $_userId;
    public function __construct($userId)
    {
        $this->_userId = $userId;
        parent::__construct("users:$userId:friends");
    }

    public function addFriend($friendId)
    {
        $this->add($friendId);
        // Add me too
        $friend = new self($friendId);
        $friend->add($this->_userId);
    }
}

// Create 2 users and make them friends
$user = new User(1);
$user->name = 'John';
$user->email = 'john@site.com';

$user = new User(2);
$user->name = 'Maria';
$user->email = 'maria@site.com';

$userFriends = new UserFriends(1);
$userFriends->addFriend(2);

?>

Also you can extend string keys for caching:

<?php

class Cache_LastPosts extends Rediska_Key
{
    public function __construct()
    {
        parent::__construct('last_posts');
    }
}

// Get from Db with Posts#getLast() and
// save to cache on 2 minutes or get from cache
// if key present and not expired

$lastPostsCache = new Cache_LastPosts();
$posts = new Posts();

$lastPosts = $lastPostsCache->getOrSetValue($posts, 2 * 60)->getLast();

foreach($lastPosts as $post) {
    echo $post;
}

?>

Comments

Fork me on GitHub