基于Predis熟悉String类型命令
client = new Predis\Client([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379
]);
// 进行连接异常处理
}
/**
* 生成blog的id(唯一ID生成器)
*/
private function createBlogId() {
return $this->client->incr('publishBlog');
}
/**
* 组装部分key前缀
*/
public function headlePrefix($id, $prefix = "") {
if(!$prefix) {
$prefix = "article:" . $id . ":";
}
return $prefix;
}
/**
* 发布blog(锁)
*/
public function publishBlog($title, $content, $author) {
$id = $this->createBlogId();
$pre = $this->headlePrefix($id);
$data = [
$pre . "title" => $title,
$pre . "content" => $content,
$pre . "author" => $author,
$pre . "createTime" => date("Y-m-d H:i:s"),
$pre . "updateTime" => "",
$pre . "likes" => 0,
$pre . "views" => 0,
];
return $this->client->msetnx($data);
}
/**
* 更新blog
*/
public function updateBlog($id, $title, $content)
{
$pre = $this->headlePrefix($id);
$data = [
$pre . "title" => $title,
$pre . "content" => $content,
$pre . "updateTime" => date("Y-m-d H:i:s"),
];
return $this->client->mset($data);
}
/**
* 查看blog
*/
public function seeBlogDetail($id, $userId) {
$pre = $this->headlePrefix($id);
if($this->client->get($pre . "title")) {
$this->client->incrby($pre . "views", 1);
}
$key = [
$pre . "title" ,
$pre . "content",
$pre . "author",
$pre . "createTime",
$pre . "likes",
$pre . "views"
];
$this->operationLog($id, $userId, __FUNCTION__);
return $this->client->mget($key);
}
// 点赞blog
public function likeBlog($id, $userId) {
$pre = $this->headlePrefix($id);
$this->operationLog($id, $userId, __FUNCTION__);
return $this->client->incr($pre . "likes");
}
/**
* 删除blog
*/
public function deleteBlog($id) {
$pre = $this->headlePrefix($id);
$data = [
$pre . "title",
$pre . "content",
$pre . "author",
$pre . "createTime",
$pre . "updateTime",
$pre . "likes",
$pre . "views",
];
return $this->client->del($data);
}
/**
* 获取blog长度
*/
public function getBlogLength($id) {
$pre = $this->headlePrefix($id);
$length = $this->client->strlen($pre . "content");
return $length;
}
/**
* 预览blog
*/
public function previewBlog($id, $userId) {
$pre = $this->headlePrefix($id);
$length = $this->client->getrange($pre . "content", 0, 24);
$this->operationLog($id, $userId, __FUNCTION__);
return $length;
}
/**
* 操作日志
*/
public function operationLog($id, $userId, $methodName){
$pre = $this->headlePrefix($id);
$title = $this->client->get($pre . "title");
$op = [
"previewBlog" => "预览",
"likeBlog" => "点赞",
"seeBlogDetail" => "查看",
];
// 用户对blog文章操作了什么。
$log = "[" . date("Y-m-d H:i:s") . " user:" . $userId . "对<" . $title .
"> 进行了" . $op[$methodName] . " ]";
$this->client->append($pre . "log", $log);
}
/**
* 获取用户对文章的操作记录
*/
public function getArticleLog($id) {
$pre = $this->headlePrefix($id);
return $this->client->get($pre . "log");
}
}