【问题标题】:Where put eloquent relationship with Repository Pattern in Laravel在 Laravel 中与 Repository Pattern 建立雄辩的关系
【发布时间】:2019-01-03 12:08:11
【问题描述】:

我正在尝试在使用 Laravel 5.6 构建的应用中学习和实现存储库模式。

我已经实现了我的控制器:

class CompaniesController extends Controller
{
    protected $company;
    public function __construct(ICompanyRepository $company) {
        $this->company = $company;
    }
    public function index(){
       $companies = $this->company->getAllCompanies();
       return view('companies::index')->with("companies", $companies);
    }
}

然后我实现了repository接口:

interface ICompanyRepository
{
    public function getAllCompanies();
    public function findBy($att, $columns);
    public function getById($id);
    public function with($relations);
}

我已经实现了我的存储库:

class CompaniesRepository implements ICompanyRepository
{
    protected $model;
    public function __construct(Companies $model){
        $this->model = $model;
    }


    public function getAllCompanies(){
        return $this->model->all();
    }
    public function findBy($att, $columns)
    {
        return $this->model->where($att, $columns);
    }

    public function getById($id)
    {
        return $this->model->findOrFail($id);
    }


    public function with($relations)
    {
        return $this->model->with($relations);

    }
}

然后我创建了模型:

class Companies extends Model
{
    protected $fillable = [];

    protected $casts = [
        'settings' => 'array'
    ];
    //my question is here!
    public function members(){
        return $this->hasMany('Companies\Entities\CompaniesMembers');
    }
}    

现在我已经将关系(在这种情况下为成员函数)放在模型中,但是通过这种方式,如果我必须更改我的 ORM,我应该同时更改存储库和模型,因为现在我使用 Eloquent,但是不知道以后会不会用 Doctrine 或者其他的。

所以我的问题是:

db 的关系和函数的最佳位置在哪里? 是全部放在模型中还是全部放在存储库中更好?

【问题讨论】:

  • 我有一个控制器、实体、eloquentrepo、接口、模型,在我的 eloquentrepo 中,我将它们组合成一个实体对象,在我看来,我使用了 getName() 之类的实体函数。这将分开所有
  • 谢谢,你能发布一个你的实现的小例子吗?
  • 是的,等几分钟;)

标签: php laravel repository-pattern


【解决方案1】:

因此,在 EloquentRepo 中,您创建了一个函数,通过 foreach 将公司与 companymembers 结合起来,并使用 modelToObject($model) 这样的东西。我希望这能帮助你找到好的方向。

EloquentRepo:

private function modelToObject($model)
{
    if (is_null($model)) {
        $entity = null;
    } else {
        $entity = new Product(
            $model->{Model::COL_ID},
            $model->{Model::COL_NAME}
        );
    }

    return $entity;
}

实体:

class Product{

    private $id;
    private $name;

    public function __construct(int $id, string $name) {
        $this->setId($id)
             ->setName($name);
    }

    public function setName(string $name): Product{
        $this->name = $name;

        return $this;
    }

    public function getName(): string {
        return $this->name;
    }
}

【讨论】:

  • 是的,但是,你不使用关系?结合 2 个模型的功能是 DB::query?还是某个模型中包含关系?
猜你喜欢
  • 2019-01-10
  • 2021-05-24
  • 2017-05-19
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
  • 2018-07-19
  • 2018-11-12
相关资源
最近更新 更多