3 回答
TA贡献1847条经验 获得超11个赞
我认为包含接口声明的所有方法的Trait是最佳选择。类似的东西(不确定逻辑):
namespace App\Repositories;
trait TDataRepository
{
// model property on class instances
protected $model;
// Constructor to bind model to repo
public function __construct(Model $model)
{
$this->model = $model;
}
// Get all instances of model
public function getAll()
{
return $this->model->all();
}
// create a new record in the database
public function create($model)
{
return $this->model->create($model);
}
// update record in the database
public function update($model)
{
$record = $this->find($model.id);
return $record->update($model);
}
// remove record from the database
public function delete($id)
{
return $this->model->destroy($id);
}
// show the record with the given id
public function getById($id)
{
return $this->model-findOrFail($id);
}
}
然后将其用于具有基本接口的类:
namespace App\Repositories;
use App\Library\Classes\Test;
use Illuminate\Database\Eloquent\Model;
class TestRepository implements ITestRepository
{
use TDataRepository;
}
TA贡献1827条经验 获得超4个赞
<?php
namespace App\Repositories;
use App\Interfaces\ITestRepository;
class TestRepository implements ITestRepository
{
public function getAll()
{
// TODO: Implement getAll() method.
}
public function getById($id)
{
// TODO: Implement getById() method.
}
public function create($model)
{
// TODO: Implement create() method.
}
public function update($model)
{
// TODO: Implement update() method.
}
public function delete($id)
{
// TODO: Implement delete() method.
}
}
类必须声明为抽象或实现方法'getAll'、'getById'、'update'、'create'、'delete' 所以默认情况下,所有方法都是接口中的抽象方法,你必须在这个类中定义所有方法。
TA贡献1818条经验 获得超11个赞
该类TestRepository不应实现任何接口,而应扩展DataRepository:
<?php namespace App\Repositories;
use App\Repositories\Data\DataRepository;
class TestRepository extends DataRepository
{
}
DataRepository已经包含接口的实现IDataRepository。当您创建一个实现类时,ITestRepository您必须定义接口中所有方法的实现(在您的情况下与基本接口相同)。
- 3 回答
- 0 关注
- 178 浏览
添加回答
举报
