【问题标题】:Laravel 5.5: Dependency Injection on user modelLaravel 5.5:用户模型的依赖注入
【发布时间】:2023-04-06 03:53:02
【问题描述】:

我有一个 BaseRepository 类,其方法对所有模型都有效。唯一的问题是,用户模型是从 use Illuminate\Foundation\Auth\User 派生的。所以它会抛出一个类型错误,因为构造函数需要一个 Illuminate\Database\Eleoquent\Model 的实例。我该如何解决这个问题?

这是我的 UserRepository.php:

namespace App\Repositories\User;

use App\Model\User; use App\Repositories\Base\BaseRepository;

class UserRepository extends BaseRepository {

public function __construct(User $user)
{
 parent::__construct($user);
}

}

BaseRepository.php

namespace App\Repositories\Base;

use App\User;
use Illuminate\Database\Eleoquent\Model;

class BaseRepository {

public function __construct (Model $model) {
    $this->model = $model;
}

public function all() {

    return $this->model->orderBy('id','desc')->get();


}


}

这是错误:类型错误: 传递给 App\Repositories\Base\BaseRepository::__construct() 的参数 1 必须是 Illuminate\Database\Eleoquent\Model 的实例,给定 App\User 的实例,在 C:\wamp64\www\adblog\ 中调用app\Repositories\User\UserRepository.ph‌​p

【问题讨论】:

  • 我认为您可以尝试使用上下文绑定。因此,当您的 UserRepository 类需要 User 时,您可以传递实际的用户实例。
  • 你注意到你的错字了吗?您的基类构造函数是否需要 Illuminate\Database\Eleoquent\Model 或 Illuminate\Database\Eloquent\Model?
  • 用户模型是Illuminate\Database\Eloquent\Model ...您使用的所有模型都是Illuminate\Database\Eloquent\Model,这就是使它们成为 Eloquent 模型的原因,它们扩展了模型。
  • 任何人,实际的错误会很好......不是你认为错误意味着什么的版本
  • 这是错误:类型错误:参数 1 传递给 App\Repositories\Base\BaseRepository::__construct() 必须是 Illuminate\Database\Eleoquent\Model 的实例,App\User 的实例给定,在 C:\wamp64\www\adblog\app\Repositories\User\UserRepository.php 中调用

标签: laravel repository-pattern


【解决方案1】:

像这样自定义您的 User 模型

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;
}

【讨论】:

  • 谢谢!但这是来自 Illuminate\Foundation\Auth 的内容
  • 是的,只是为了让您的用户模型扩展 Eloquent\Model 而不是 Illuminate\Foundation\Auth\User?
  • 我认为这不能解决问题。用户是 Illuminate\Database\Eloquent\Model 类型,因为它扩展了这个类。
  • “构造函数需要一个 Illuminate\Database\Eloquent\Model 的实例”,正如 OP 所说的
  • 是的,但是“Illuminate\Foundation\Auth\User as Authenticatable”继承自“model”类
猜你喜欢
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 2021-04-17
  • 2016-02-11
  • 1970-01-01
  • 2022-01-16
相关资源
最近更新 更多