houdunwang / repository
仓库模式
v1.0.2
2018-06-30 21:16 UTC
Requires
- php: >=7.0
- nwidart/laravel-modules: ^3.3
Requires (Dev)
- phpunit/phpunit: ^6.1
This package is auto-updated.
Last update: 2024-09-13 05:27:51 UTC
README
houdunren.com @ 向军大叔
项目地址:https://packagist.org.cn/packages/houdunwang/repository
仓库模式的主要思想是建立一个数据操作代理层,将控制器中的数据操作剥离出来。
仓库模式是一种架构模式,只有在设计架构时才有参考价值。应用仓库模式带来的好处远大于实现模式所增加的代码。只要项目分层,都应该使用这个模式。
这样做有几个好处:
- 将数据处理逻辑分离,使得代码更容易维护
- 数据处理逻辑和业务逻辑分离,可以对这两个代码分别进行测试
- 减少代码重复
- 降低代码出错的几率
- 大大提高控制器代码的可读性
安装
composer require houdunwang/repository:dev-master
接口方法
//查找单条
public function find($id);
//获取所有
public function all();
//分页数据
public function paginate($page = 15);
//新增模型
public function create($data);
//更改模型
public function update($model, $data);
//删除模型
public function destroy($model);
//根据属性条件查询
public function findByAttributes(array $attributes);
//多个主键数据
public function findByMany(array $ids);
//根据属性条件获取多条
public function getByAttributes(array $attributes, $orderBy = null, $sortOrder = 'asc');
//清除缓存(缓存仓库有效)
public function clearCache();
模型仓库
模型仓库是对数据模型的管理中间件。
声明仓库
namespace App\Repositories\Eloquent;
use Houdunwang\Repository\EloquentBaseRepository;
class ConfigRepository extends EloquentBaseRepository
{
}
使用仓库
namespace App\Http\Controllers;
use App\Models\Config;
use App\Repositories\Eloquent\ConfigRepository;
class HomeController extends Controller
{
public function __construct(Config $config)
{
$repository = new ConfigRepository($config);
dd($repository->find(1));
}
...
缓存仓库
缓存仓库与模型仓库区别不大,只是增加了一个缓存中间层对数据进行缓存处理。当模型数据发生变化时,自动更新缓存。
声明仓库
namespace App\Repositories\Cache;
use Houdunwang\Repository\CacheBaseRepository;
class ConfigRepository extends CacheBaseRepository
{
}
使用仓库
namespace App\Http\Controllers;
use App\Models\Config;
use App\Repositories\Eloquent\ConfigRepository;
class HomeController extends Controller
{
public function __construct(Config $config)
{
$repository = new ConfigRepository($config);
dd($repository->find(1));
}
...