如何解决如何缓存 auth()->user() 与 Laravel 缓存中的角色等关系以减少对 DB 的调用?
我正在构建一个使用 lighthouse-php 的应用程序。因为我不断为不同的用户设置各种策略,我在不同的部分应用程序中不断查询具有角色关系的用户模型,因此,希望将用户存储在Redis数据库中并从那里查询。 我阅读了我在互联网上找到的几篇文章,例如:laravel-cache-authuser; creating-a-caching-user-provider-for-laravel/; caching-the-laravel-user-provider-with-a-decorator/,查看了此处的代码 laravel-auth-user,有点理解这个概念,但很难深入理解 Laravel 以找到合适的解决方案......
例如,我很难理解如何在 UserObserver 中的事件方法内存储 User
与 Role
关系,很清楚如何使用一个模型而不是附加关系来做到这一点。>
我有一种感觉,我应该做这样的事情:
class UserObserver
{
/**
* @param User $user
*/
public function saved(User $user)
{
$user->load('role');
Cache::put("user.$user->id",$user,60);
}
}
但是这样我对数据库进行了 2 次调用,而不是预先加载关系。我怎么能在事件参数中预加载关系。我尝试添加 protected $with = ['role']
以便始终加载子模型/关系。但无论我如何调用 DB 来检索角色或检索用户和角色。
他是我的项目 lighthouse-php 中的一些简化代码示例。
schema.graphql:
type SomeType {
someMethod(args: [String!]): [Model!] @method @can(ability: "isAdmin",model: "App\\Models\\User")
}
type User {
id: ID
name: String
role: Role @belongsTo
}
type Role {
id: ID!
name: String!
label: String!
users: [User!] @hasMany
}
具有角色关系的用户模型:
class User extends Authenticatabl {
public function role(): BelongsTo
{
return $this->belongsTo(Role::class);
}
}
用于一些 graphql 类型字段的用户策略:
class UserPolicy
{
use HandlesAuthorization;
public function isAdmin(): Response
{
$user = auth()->user();
return $user->role->name === 'admin'
? $this->allow()
: $this->deny('permission denied');
}
public function isManager(): Response
{
$user = auth()->user();
$this->allow();
return $user->role->name === 'manager' || $user->role->name === 'admin'
? $this->allow()
: $this->deny('Permission Denied');
}
}
Lighouse 自定义查询类,用于通过方法解析字段。
class SomeType {
public function someMethod(): string
{
// this triggers db call rather than receiving `role->name` from redis along with user
return auth()->user()->role->name;
}
}
如果我进行类似这样的 graphql 查询(请参见下文),它会导致从数据库加载角色关系,而不是从缓存加载。
query {
user {
id
name
role {
id
name
}
}
}
Please help.
解决方法
您可以通过为 accessor
模型上的 role
属性创建自定义 User
来缓存关系。一个例子可能是:
<?php
use Illuminate\Support\Facades\Cache;
class User extends Authenticatabl {
public function role(): BelongsTo
{
return $this->belongsTo(Role::class);
}
public static function getRoleCacheKey(User $user): string
{
return sprintf('user-%d-role',$user->id);
}
// Define accessor for caching purposes
public function getRoleAttribute(): Collection
{
if ($this->relationLoaded('role')) {
return $this->getRelationValue('role');
}
// Replace 3600 for the amount of seconds you would like to cache
$role = Cache::remember(User::getRoleCacheKey($this),3600,function () {
return $this->getRelationValue('role');
});
$this->setRelation('role',$role);
return $role;
}
}
或者,您可以使用 rememberForever()
函数永久缓存它。请注意,您必须编写一个实现来手动删除/更新缓存,因为它将永远保存该值。您可以创建一个清除缓存的函数,如下所示:
// In User model
public static function forgetRoleCaching(User $user): bool
{
return Cache::forget(sprintf(User::getRoleCacheKey($user));
}
您在观察者中的代码可以更新为以下内容:
class UserObserver
{
/**
* @param User $user
*/
public function saved(User $user)
{
// in case user role is cached forever
User::forgetRoleCaching($user);
$user->load('role'); // will trigger the accessor an should cache again
Cache::put("user.$user->id",$user,60);
}
}
,
您可以使用 Session 存储您的 auth 用户与您的关系。
示例:
$auth = Auth::User();
Session::put('user',$auth);
Session::put('relation',$auth->relation);
希望对你有帮助
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。