我正在尝试在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
。任何人都可以解决吗?
public function getRoleServiceAttribute ()
{
if(is_null($this->roleService)){
$this->roleService = resolve(RoleService::class);
}
return $this->roleService;
}
Model
类中进行依赖注入,因为它会破坏项目结构。项目应遵循以下结构:Controller
-> Service
-> Repository
-> Model
-> Database
。因此,我将按照它重构我的代码。