无法在Laravel中为Model类设置属性

问题描述 投票:0回答:2

我正在尝试在User类上添加依赖项注入,经过数小时的尝试,我发现这种方式:

  • 我将此代码添加到App\Models\User
    public function __construct()
    {
        $this->roleService = resolve(RoleService::class);
    }
  • 我已经检查过$this->roleService值,它可以正常工作,当我尝试在函数中使用它时会提示:
    public function isAdmin() {
        return $this->roleService->isAdmin($this->role_id);
    }
  • 此函数抛出错误Call to a member function isAdmin() on null。当我登录$this->roleService时,它返回了null

任何人都可以解决吗?

laravel dependency-injection model laravel-6
2个回答
0
投票
为模型创建自定义访问器,并从那里获取/设置值。

public function getRoleServiceAttribute () { if(is_null($this->roleService)){ $this->roleService = resolve(RoleService::class); } return $this->roleService; }


0
投票
感谢您的帮助。我只是参考了专家的回答。他说我们不应该在Model类中进行依赖注入,因为它会破坏项目结构。项目应遵循以下结构:Controller-> Service-> Repository-> Model-> Database。因此,我将按照它重构我的代码。
© www.soinside.com 2019 - 2024. All rights reserved.