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 關注
- 111 瀏覽
添加回答
舉報