doumeng2637 2018-08-14 14:54
浏览 84

如何在laravel中缓存函数的结果

I would like to know if it is possible to store the results of a function in cache for each possible outcome.

This is not an exact example below, the real example is a lot more complex and I need to cache the results for speed reasons, but this gives you an idea of what I'm trying to accomplish

For example I have a function that retrieves the users comments:

public function getUserComments(User $user)
{
    $comments = DB::table('comments')->where('user_id',$user->id)->get();
    return $comments;
}

I need to save all the possible outcomes for each individual user in my system so essentially.

For example if I have 100 users:

foreach ($users as $user) {
       $cachedResults [] = $user->getUserComments();
}

Now I have the cached results that are faster to look through: $cachedResults

  • 写回答

2条回答 默认 最新

  • doudiejian5827 2018-08-14 15:11
    关注

    Something like this should do the trick(not tested):

    public function getUserComments(User $user)
    {
        $key = "comments-${$user->id}";
    
        $comments = Cache::remember($key, 60, function () {
            return DB::table('comments')->where('user_id',$user->id)->get();
        });
    
        return $comments
    }
    

    60 is the amount of minutes here. You have to configure your cache if you want something other than the default, which is the file cache driver.

    评论

报告相同问题?