Laravel - 存储库模式问题
我有我的Laravel应用程序使用存储库模式。我也有一个叫做EloquentRepository
的抽象类,它包含基本的方法。我所有的资料库中有一个update()
方法,在这里我简单的使用ID和阵列更新模型:Laravel - 存储库模式问题
abstract class EloquentRepository {
public function update($id, array $array) {
$this->model->whereId($id)->update($array);
}
}
现在,我也有一个Server
库:
interface ServerRepository {
public function update($id, array $options);
}
class EloquentServerRepository extends EloquentRepository implements ServerRepository {
protected $model;
public function __construct(Server $model)
{
$this->model = $model;
}
}
所以,现在,我不不得不将update()
方法添加到我的EloquentServerRepository
,也不需要任何其他需要执行此操作的存储库(相当多)。
但是,有一个存储库具有更新功能,但我希望它做一些“自定义”的事情。可以说这是用户存储库:
interface UserRepository {
public function update($id, array $options, $status);
}
class EloquentUserRepository extends EloquentRepository implements UserRepository {
protected $model;
public function __construct(User $model)
{
$this->model = $model;
}
public function update($id, array $options, $status)
{
$this->model->setStatus($status);
$this->model->whereId($id)->update($options);
}
}
所以现在,我有我的用户存储库要求每个更新的状态。
但是,我得到的错误:
Declaration of EloquentUserRepository::update() should be compatible with EloquentRepository::update($id, array $array)
。
为什么这个,当然我的接口指定了声明应该是什么?
您可以通过$状态可选获得通过的错误所赋予它的默认值,例如:
public function update($id, array $options, $status = null)
没有它是可选的(默认值),你说的这个方法需要有一个第三个参数,违反合同由ServerRepository
这是因为要扩展EloquentUserRepository
,你有update
方法是这样设置:
public function update($id, array $array) {
$this->model->whereId($id)->update($array);
}
在这种情况下,你也实现了UserRepository
接口,但根据基类的update
方法您update
方法具有不同的签名,这是下面给出:
public function update($id, array $options, $status);
因此,误差上升的原因你有不同的方法签名。虽然你可能可以使这两个方法的签名同样可能使用的可选参数是这样的:
// EloquentUserRepository
public function update($id, array $array, $status = null) {
$this->model->whereId($id)->update($array);
}
// interface UserRepository
interface UserRepository {
public function update($id, array $options, $status = null);
}
但我会建议只使用一个接口或抽象类和覆盖的方法在你EloquentUserRepository
对于不同的使用情况。这将是这样的:
abstract class EloquentRepository {
public function update($id, array $array, $status = null) {
$this->model->whereId($id)->update($array);
}
}
// Only extend the EloquentRepository and override the update method
class EloquentUserRepository extends EloquentRepository {
protected $model;
public function __construct(User $model)
{
$this->model = $model;
}
// re-declare the method to override
public function update($id, array $options, $status = null)
{
$this->model->setStatus($status);
$this->model->whereId($id)->update($options);
}
}
或更改EloquentRepository
一点,例如:
abstract class EloquentRepository {
public function update($id, array $array, $status = null) {
if(!is_null($status)) {
$this->model->setStatus($status);
}
$this->model->whereId($id)->update($array);
}
}