У меня есть 3 модели для управления разрешениями пользователей.Laravel - Реализация красноречивых отношений в репозитории
class User extends Authenticatable
{
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
}
class Role extends Model
{
public function users()
{
return $this->belongsToMany('App\Models\User');
}
public function permissions()
{
return $this->belongsToMany('App\Models\Permission');
}
}
class Permission extends Model
{
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
public function roleHavePermission(Role $role)
{
if ($this->roles()->find($role->id)) {
return true;
}
return false;
}
public function userHavePermission(User $user = null)
{
$roles = [];
if (is_null($user)) {
$roles[] = Role::where('slug', 'guest')->first();
} else {
foreach ($user->roles as $role) {
$roles[] = $role;
}
}
foreach ($roles as $role) {
if ($this->roleHavePermission($role)) {
return true;
}
}
return false;
}
}
Теперь, поскольку мое приложение выросло, я перехожу к хранилищам. Например, это мой PermissionRepository
:
class PermissionRepository implements PermissionRepositoryInterface
{
protected $roleRepository;
/**
* PermissionRepository constructor.
* @param RoleRepositoryInterface $roleRepository
*/
public function __construct(RoleRepositoryInterface $roleRepository)
{
$this->roleRepository = $roleRepository;
}
public function action($routeName)
{
return Permission::where('action', $routeName)->first();
}
}
Как я могу реализовать roleHavePermission
и userHavePermission
в этом хранилище? Я попытался реализация roles
метода с этим синтаксисом:
public function roles()
{
return Permission::roles();
}
Но это не будет работать, так как метод ролей разрешения не может назвать статический. Благодарю.
Удивительный! Спасибо! – ma3x