static静态变量缓存
日常开发中,经常使用到缓存来减少数据库的压力,如redis缓存等等方案,其实使用static静态变量,来当作是我们数据的一级缓存也是我们常常使用的一种方案。
使用场景: 在一次请求中,某个数据被多次不同的方法来使用,而你不想多次读redis或者db来增加你的I/O消耗,又不想把他当做参数传来传去,这个时候static就是非常好的解决方案。
/**
* 获取章节ids
* @param $audioId
* @return array|mixed
*/
public function getChapterIds($bookId)
{
//静态缓存
if (self::$chapterIds) {
return self::$chapterIds;
}
// 静态缓存没有则查redis
....
// redis中没有则查询db,缓存redis
....
// 静态缓存
self::$chapterIds = $ids;
return $ids;
}
/**
* 取下一章节id
* @param $audioId
* @param $chapterId
* @return int
*/
public function getNextChapterId($bookId, $chapterId)
{
$ids = $this->getChapterIds($bookId);
// 其他操作
// ....
}
/**
* 取上一章节id
* @param $audioId
* @param $chapterId
* @return int
*/
public function getLastChapterId($bookId, $chapterId)
{
$ids = $this->getChapterIds($bookId);
// 其他操作
// ....
}
/**
* 取章节数据
* @param $chapterId
* @param array $fields
* @return array|mixed
*/
public function getChapterInfo($chapterId, $fields=[])
{
// 获取上章节和下章节
$chapter['last_chapter'] = $this->getLastChapterId($chapter['book_id'], $chapter['chapter_id']);
$chapter['next_chapter'] = $this->getNextChapterId($chapter['book_id'], $chapter['chapter_id']);
// TODO 其他操作
// ....
return $chapter;
}