Php 如何缓存当前经过身份验证的用户? 描述
在我的情况下,我没有本地的Php 如何缓存当前经过身份验证的用户? 描述,php,laravel,Php,Laravel,在我的情况下,我没有本地的users表,但是我有一个api,它将为我提供一个用户列表 getUsers() 我在app/Auth/ApiUserProvider.php protected function getUsers() { $ch = curl_init(); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
users
表,但是我有一个api,它将为我提供一个用户列表
getUsers() 我在
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
它会影响我的应用程序的很多延迟
试试看 会话
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秒钟(
我如何解决这个问题 我应该开始使用缓存吗?如果是,我如何修改我必须做的事情 我应该将其存储在会话中吗 我现在愿意接受任何建议 如果您对此有任何提示/建议,我们将不胜感激!您可以这样做
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;
}
这应该行得通
有时,您可能希望从缓存中检索项目,但是
如果请求的项不存在,则存储默认值
-拉威尔博士
您将从缓存中获取用户,或者,如果用户不存在,则从api中检索用户并将其添加到缓存中尝试以下操作:我已经进行了自定义身份验证,我正在尝试缓存我的
auth::user()
object,这样我就不必一直点击我的API。快速提问,这样会话就不起作用了?好的。我会试试catch。我想这会更有效。这很公平。:)如果{这对你有用/或者这就是你要找的,别忘了按答案勾选它}否则{我希望你找到正确的解决方案}等等,我犯了一个错误,il fix answer(当您返回response[data]时,$user变量将包含数据(如果可用,则来自缓存或api),然后返回$user(php方法的返回)并尝试dd($user,在返回之前检查您是否有数据)