2016-04-30 31 views
0

描述

在我的情况,我没有在本地users表,但我有一个API将提供我一个用户列表。如何缓存当前已通过身份验证的用户? (Laravel 5)


getUsers()

修改我getUsers()Auth::user()app/Auth/ApiUserProvider.php

protected function getUsers() 
{ 
    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts'); 

    $response = curl_exec($ch); 
    $response = json_decode($response, true); 

    curl_close($ch); 

    return $response['data']; 
} 

问题

每一次,我在我的代码使用Auth::user()。它打电话给我的API .../vse/accounts 它在我的应用程序中造成了很多延迟。


尝试#1

会话

protected function getUsers() 
{ 

    if(Session::has('user')){ 
     return Session::get('user'); 
    }else{ 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts'); 
     $response = curl_exec($ch); 
     $response = json_decode($response, true); 
     curl_close($ch); 
     $user = $response['data']; 
     Session::put('user',$user); 
     return $user; 
    } 

} 

结果

它需要2秒。 :(


尝试#2

缓存

protected function getUsers() 
{ 
    $minutes = 60; 
    $value = Cache::remember('user', $minutes, function() { 
     //your api stuff 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts'); 
     $response = curl_exec($ch); 
     $response = json_decode($response, true); 
     curl_close($ch); 
     $user = $response['data']; 
     return $user; 
    }); 
} 

我该如何解决这个问题?

我应该开始使用缓存?如果是这样,怎么办我修改了我必须做的事情吗?

我应该将它存储在会话中吗?

我接受任何建议,现在。

任何提示/建议,将非常感谢!

+0

试试这个:http:// laravel。io/forum/11-04-2014-laravel-5-how-do-i-create-a-custom-auth-in-laravel-5 –

+0

我已经做了自定义认证,我试图缓存我的'认证: :user()'对象,所以我不必一直打我的API。 – ihue

回答

1

你可以做到这一点

protected function getUsers() { 
    $minutes = 60; 
    $user = Cache::remember('user', $minutes, function() { 
     //your api stuff 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts'); 
     $response = curl_exec($ch); 
     $response = json_decode($response, true); 
     curl_close($ch); 
     return $response['data']; 
    }); 
     return $user; 
} 

这应该工作

有时你可能希望从缓存中检索一个项目,也是 店默认值,如果请求的项目不存在 -laravel文档

您将从缓存中获取用户,或者如果他不存在,检索用户从api,并将他添加到缓存

+0

快速问题,所以会话将不起作用?好。我会尝试抓住。 – ihue

+0

我认为这样会更有效率 –

+0

好的。很公平。 :) – ihue

相关问题