Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 存储库模式-存储库可以包含除核心CRUD之外的逻辑吗_Php_Laravel_Repository Pattern - Fatal编程技术网

Php 存储库模式-存储库可以包含除核心CRUD之外的逻辑吗

Php 存储库模式-存储库可以包含除核心CRUD之外的逻辑吗,php,laravel,repository-pattern,Php,Laravel,Repository Pattern,因此,我理解使用存储库模式有多种原因,其中之一是抽象与数据源的交互 我的问题是,存储库方法应该是简单的还是复杂的。是一个纯粹用于抽象核心方法的存储库,例如获取、设置、更新、删除数据源,或者可以向存储库添加非常特殊的方法,例如getCountOfUseThatAreDisabled。我的意思是,像这样的方法应该放在图片中的什么位置,或者我应该把它们放在repository类之外 // Laravel Example protected $user; // public function

因此,我理解使用存储库模式有多种原因,其中之一是抽象与数据源的交互

我的问题是,存储库方法应该是简单的还是复杂的。是一个纯粹用于抽象核心方法的存储库,例如获取、设置、更新、删除数据源,或者可以向存储库添加非常特殊的方法,例如
getCountOfUseThatAreDisabled
。我的意思是,像这样的方法应该放在图片中的什么位置,或者我应该把它们放在repository类之外

// Laravel Example    

protected $user; //

public function __construct(User $user){
     $this->user = $user;
}

public function getCountOfUsersThatAreDisabled(){
     $this->user->where('disabled', 1);
}

public function find($user_id){ 
     return $this->user->find($user_id);
}

您的方式很好,将您与模型代码的交互放在存储库中是完全可以的,事实上,这绝对是应该的方式

但按照你的方法:

public function getCountOfUsersThatAreDisabled(){
     $this->user->where('disabled', 1);
}
我更喜欢缩短方法名,并添加where方法参数作为主要方法参数

public function getCountOfUsers(array $where=["disabled", 1]){
     call_user_func_array([$this->user, "where"] , $where);
}
通过这种方式,您的方法更具可读性和通用性,您也可以将其用于不同的WHERE值,即使您希望向WHERE方法传递两个以上的参数(例如:$WHERE=[“id”,“>”,100])


希望这能有所帮助。

…或者可以向存储库中添加一些非常小的方法,比如getCountOfUstHatDisabled
,这是可以的,也是常见的做法。这就是这些类型的东西应该去的地方。好的,酷。我不熟悉整个存储库的概念,只是确保我做得正确,不会使存储库类过于复杂。存储库方法是否可以同时包含最终用于返回结果的sql和过程代码。是的,存储库的全部目的是为应用程序提供一个标准接口来检索数据。只要返回相同的数据,您的方法就可以基于ORM模型、查询生成器或原始SQL查询