Lumen7.x 使用笔记(五)Repository仓库

作者: 太阳上的雨天 分类: Lumen7.x使用教程,PHP 发布时间: 2020-09-30 15:43

Lumen7.x 使用笔记(五)Repository仓库

使用 Repository 模式实现业务逻辑和数据访问的分离

按照最初提出者的介绍,Repository 是衔接数据映射层和领域层之间的一个纽带,作用相当于一个在内存中的域对象集合。客户端对象把查询的一些实体进行组合,并把它 们提交给 Repository。对象能够从 Repository 中移除或者添加,就好比这些对象在一个 Collection 对象上进行数据操作,同时映射层的代码会对应的从数据库中取出相应的数据。

从概念上讲,Repository 是把一个数据存储区的数据给封装成对象的集合并提供了对这些集合的操作。

Repository 模式将业务逻辑和数据访问分离开,两者之间通过 Repository 接口进行通信,通俗点说,可以把 Repository 看做仓库管理员,我们要从仓库取东西(业务逻辑),只需要找管理员要就是了(Repository),不需要自己去找(数据访问)

目录结构

app/Contracts 目录存放接口

app/Repository 目录存放数据仓库

定义接口 Interface

要实现 Repository 模式,首先需要定义接口,这些接口就像 Laravel 中的契约一样,需要具体类去实现

在app/Contracts目录下新建RepositoryInterface

<?php
namespace App\Contracts;

interface RepositoryInterface
{
    /**
     * Notes: 所有数据
     * User: clj
     * Date: 2020/9/18
     * Time: 6:54 下午
     * @param string[] $columns
     * @return mixed
     */
    public function all($columns = array('*'));

    /**
     * Notes: 分页查询
     * User: clj
     * Date: 2020/9/18
     * Time: 6:54 下午
     * @param int $perPage
     * @param string[] $columns
     * @return mixed
     */
    public function paginate($perPage = 15, $columns = array('*'));

    /**
     * Notes: 新增数据
     * User: clj
     * Date: 2020/9/18
     * Time: 6:54 下午
     * @param array $data
     * @return mixed
     */
    public function create(array $data);

    /**
     * Notes: 更新数据
     * User: clj
     * Date: 2020/9/18
     * Time: 6:54 下午
     * @param array $data
     * @param $id
     * @return mixed
     */
    public function update(array $data, $id);

    /**
     * Notes: 删除数据
     * User: clj
     * Date: 2020/9/18
     * Time: 6:55 下午
     * @param $id
     * @return mixed
     */
    public function delete($id);

    /**
     * Notes: 查找一条数据
     * User: clj
     * Date: 2020/9/18
     * Time: 6:55 下午
     * @param $id
     * @param string[] $columns
     * @return mixed
     */
    public function find($id, $columns = array('*'));

    /**
     * Notes: 根据字段查找数据
     * User: clj
     * Date: 2020/9/18
     * Time: 6:55 下午
     * @param $field
     * @param $value
     * @param string[] $columns
     * @param array $map
     * @return mixed
     */
    public function findBy($field, $value, $columns = array('*'), array $map = []);

    /**
     * Notes: getBy
     * User: clj
     * Date: 2020/9/21
     * Time: 8:57 下午
     * @param $field
     * @param $value
     * @param string[] $columns
     * @return mixed
     */
    public function getBy($field, $value, $columns = array('*'));

    /**
     * Notes: getByField
     * User: cc
     * Date: 2020/9/22
     * Time: 1:28 下午
     * @param string $field
     * @param string $value
     * @param string[] $columns
     * @return mixed
     */
    public function getByField(string $field, string $value, $columns = array('*'));

    /**
     * Notes: findWhereIn
     * User: clj
     * Date: 2020/9/19
     * Time: 1:53 下午
     * @param $field
     * @param $value
     * @param string[] $columns
     * @return mixed
     */
    public function findWhereIn($field, $value, $columns = array('*'));

    /**
     * Notes: findWhereNotIn
     * User: clj
     * Date: 2020/9/19
     * Time: 1:54 下午
     * @param $field
     * @param $value
     * @param string[] $columns
     * @return mixed
     */
    public function findWhereNotIn($field, $value, $columns = array('*'));

    /**
     * Notes: findWhereBetween
     * User: clj
     * Date: 2020/9/19
     * Time: 1:54 下午
     * @param $field
     * @param $value
     * @param string[] $columns
     * @return mixed
     */
    public function findWhereBetween($field, $value, $columns = array('*'));

    /**
     * Notes: updateOrCreated
     * User: clj
     * Date: 2020/9/19
     * Time: 1:54 下午
     * @param array $attributes
     * @param array $values
     * @return mixed
     */
    public function updateOrCreated(array $attributes, array $values = []);

    /**
     * Notes: orderBy
     * User: clj
     * Date: 2020/9/19
     * Time: 1:54 下午
     * @param $column
     * @param string $direction
     * @return mixed
     */
    public function orderBy($column, $direction = 'asc');

    /**
     * Notes: with
     * User: clj
     * Date: 2020/9/19
     * Time: 1:54 下午
     * @param $relations
     * @return mixed
     */
    public function with($relations);

    /**
     * Notes: withCount
     * User: clj
     * Date: 2020/9/19
     * Time: 1:54 下午
     * @param $relations
     * @return mixed
     */
    public function withCount($relations);

    /**
     * Notes: withHas
     * User: clj
     * Date: 2020/9/19
     * Time: 1:55 下午
     * @param $relation
     * @param $closure
     * @return mixed
     */
    public function withHas($relation, $closure);

    /**
     * Notes: join
     * User: cc
     * Date: 2020/9/22
     * Time: 1:06 下午
     * @param string $table
     * @param string $one
     * @param string $operator
     * @param string[] $columns
     * @param string $two
     * @param array $where
     * @return mixed
     */
    public function join(string $table, string $one, string $operator = '=', $columns = array('*'), string $two = '', array $where=[]);

    /**
     * Notes: leftJoin
     * User: cc
     * Date: 2020/9/22
     * Time: 1:00 下午
     * @param string $table
     * @param string $one
     * @param string $operator
     * @param string[] $columns
     * @param string $two
     * @param array $where
     * @return mixed
     */
    public function leftJoin(string $table, string $one, string $operator = '=', $columns = array('*'), string $two = '', array $where = []);

    /**
     * Notes: rightJoin
     * User: cc
     * Date: 2020/9/22
     * Time: 1:03 下午
     * @param string $table
     * @param string $one
     * @param string $operator
     * @param string[] $columns
     * @param string $two
     * @param array $where
     * @return mixed
     */
    public function rightJoin(string $table, string $one, string $operator = '=', $columns = array('*'), string $two = '', array $where = []);

    /**
     * Notes: max
     * User: cc
     * Date: 2020/9/22
     * Time: 1:33 下午
     * @param string $field
     * @return int
     */
    public function max(string $field): int;

    /**
     * Notes: count
     * User: cc
     * Date: 2020/9/22
     * Time: 1:36 下午
     * @param string $field
     * @return int
     */
    public function count(string $field): int;

    /**
     * Notes: avg
     * User: cc
     * Date: 2020/9/22
     * Time: 1:39 下午
     * @param string $field
     * @return int
     */
    public function avg(string $field): int;

    /**
     * Notes: whereNull
     * User: cc
     * Date: 2020/9/22
     * Time: 1:47 下午
     * @param string $field
     * @param string[] $columns
     * @return mixed
     */
    public function whereNull(string $field, $columns = array('*'));

    /**
     * Notes: whereNotNull
     * User: cc
     * Date: 2020/9/22
     * Time: 1:47 下午
     * @param string $field
     * @param string[] $columns
     * @return mixed
     */
    public function whereNotNull(string $field, $columns = array('*'));

    /**
     * Notes: min
     * User: cc
     * Date: 2020/9/22
     * Time: 1:34 下午
     * @param string $field
     * @return int
     */
    public function min(string $field): int;

}

定义抽象类

在app\Repository目录下新建AbstractRepository实现上面的接口

<?php
namespace App\Repository;

use App\Contracts\RepositoryInterface;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

abstract class AbstractRepository implements RepositoryInterface
{

    /**
     * @var mixed
     */
    protected $model;

    /**
     * Notes: All
     * User: clj
     * Date: 2020/9/18
     * Time: 8:01 下午
     * @param string[] $columns
     * @return Collection|Model[]|mixed
     */
    public function all($columns = array('*'))
    {
        return $this->model->all($columns);
    }

    /**
     * Notes: paginate
     * User: clj
     * Date: 2020/9/18
     * Time: 8:02 下午
     * @param int $perPage
     * @param string[] $columns
     * @return mixed
     */
    public function paginate($perPage = 15, $columns = array('*'))
    {
        return $this->model->paginate($perPage, $columns);
    }

    /**
     * Notes: create
     * User: clj
     * Date: 2020/9/18
     * Time: 8:48 下午
     * @param array $data
     * @return mixed
     */
    public function create(array $data)
    {
        return $this->model->create($data);
    }

    /**
     * Notes: update
     * User: clj
     * Date: 2020/9/18
     * Time: 8:48 下午
     * @param array $data
     * @param $id
     * @param string $attribute
     * @return mixed
     */
    public function update(array $data, $id, $attribute='id')
    {
        return $this->model->where($attribute, '=', $id)->update($data);
    }

    /**
     * Notes: delete
     * User: clj
     * Date: 2020/9/18
     * Time: 8:48 下午
     * @param $id
     * @return bool|mixed|null
     * @throws Exception
     */
    public function delete($id)
    {
        return $this->model->delete($id);
    }

    /**
     * Notes: find
     * User: clj
     * Date: 2020/9/18
     * Time: 8:49 下午
     * @param $id
     * @param string[] $columns
     * @return mixed
     */
    public function find($id, $columns = array('*'))
    {
        return $this->model->find($id, $columns);
    }

    /**
     * Notes: findBy
     * User: clj
     * Date: 2020/9/18
     * Time: 8:49 下午
     * @param $attribute
     * @param $value
     * @param string[] $columns
     * @param array $map
     * @return mixed
     */
    public function findBy($attribute, $value, $columns = array('*'), array $map = [])
    {
        return $this->model->where($attribute, '=', $value)->where($map)->first($columns);
    }

    /**
     * Notes: getBy
     * User: cc
     * Date: 2020/9/21
     * Time: 8:57 下午
     * @param $attribute
     * @param $value
     * @param string[] $columns
     * @return mixed
     */
    public function getBy($attribute, $value, $columns = array('*'))
    {
        return $this->model->where($attribute, '=', $value)->get();
    }

    /**
     * Notes: getByField
     * User: cc
     * Date: 2020/9/22
     * Time: 1:28 下午
     * @param string $field
     * @param string $value
     * @param string[] $columns
     * @return mixed
     */
    public function getByField(string $field, string $value, $columns = array('*'))
    {
        return $this->model->where($field, 'like', '%' . $value . '%')->get();
    }

    /**
     * Notes: findWereIn
     * User: clj
     * Date: 2020/9/19
     * Time: 1:59 下午
     * @param $field
     * @param $value
     * @param string[] $columns
     * @return mixed
     */
    public function findWhereIn($field, $value, $columns = array('*'))
    {
        return $this->model->whereIn($field, $value)->get($columns);
    }

    /**
     * Notes: findWhereNotIn
     * User: clj
     * Date: 2020/9/21
     * Time: 8:43 上午
     * @param $field
     * @param $value
     * @param string[] $columns
     * @return mixed
     */
    public function findWhereNotIn($field, $value, $columns = array('*'))
    {
        return $this->model->whereNotIn($field, $value)->get($columns);
    }

    /**
     * Notes: findWhereBetween
     * User: clj
     * Date: 2020/9/21
     * Time: 8:44 上午
     * @param $field
     * @param $value
     * @param string[] $columns
     * @return mixed
     */
    public function findWhereBetween($field, $value, $columns = array('*'))
    {
        return $this->model->whereBetween($field, $value)->get($columns);
    }

    /**
     * Notes: updateOrCreated
     * User: clj
     * Date: 2020/9/21
     * Time: 8:44 上午
     * @param array $attributes
     * @param array $values
     * @return mixed
     */
    public function updateOrCreated(array $attributes, array $values = [])
    {
        return $this->model->updateOrCreate($attributes, $values);
    }

    /**
     * Notes: orderBy
     * User: clj
     * Date: 2020/9/21
     * Time: 8:44 上午
     * @param $column
     * @param string $direction
     * @return mixed
     */
    public function orderBy($column, $direction = 'asc')
    {
        return $this->model->orderBy($column, $direction);
    }

    /**
     * Notes: with
     * User: clj
     * Date: 2020/9/21
     * Time: 8:44 上午
     * @param $relations
     * @return mixed
     */
    public function with($relations)
    {
        return $this->with($relations);
    }

    /**
     * Notes: withCount
     * User: clj
     * Date: 2020/9/21
     * Time: 8:44 上午
     * @param $relations
     * @return mixed
     */
    public function withCount($relations)
    {
        return $this->model->withCount($relations);
    }

    /**
     * Notes: withHas
     * User: clj
     * Date: 2020/9/21
     * Time: 8:44 上午
     * @param $relation
     * @param $closure
     * @return mixed
     */
    public function withHas($relation, $closure)
    {
        return $this->model->withHas($relation, $closure);
    }

    /**
     * Notes: join
     * User: cc
     * Date: 2020/9/22
     * Time: 1:08 下午
     * @param string $table
     * @param string $one
     * @param string $operator
     * @param string[] $columns
     * @param string $two
     * @param array $where
     * @return mixed
     */
    public function join(string $table, string $one, string $operator = '=', $columns = array('*'), string $two = '', array $where = [])
    {
        return $this->model->where($where)->join($table, $one, $operator, $two)->select($columns)->get();
    }

    /**
     * Notes: leftJoin
     * User: cc
     * Date: 2020/9/22
     * Time: 1:03 下午
     * @param string $table
     * @param string $one
     * @param string $operator
     * @param string[] $columns
     * @param string $two
     * @param array $where
     * @return mixed
     */
    public function leftJoin(string $table, string $one, string $operator = '=', $columns = array('*'), string $two = '', array $where = [])
    {
        return $this->model->where($where)->leftJoin($table, $one, $operator, $two)->select($columns)->get();
    }

    /**
     * Notes: rightJoin
     * User: cc
     * Date: 2020/9/22
     * Time: 1:03 下午
     * @param string $table
     * @param string $one
     * @param string $operator
     * @param string[] $columns
     * @param string $two
     * @param array $where
     * @return mixed
     */
    public function rightJoin(string $table, string $one, string $operator = '=', $columns = array('*'), string $two = '', array $where = [])
    {
        return $this->model->where($where)->rightJoin($table, $one, $operator, $two)->select($columns)->get();
    }

    /**
     * Notes: max
     * User: cc
     * Date: 2020/9/22
     * Time: 1:33 下午
     * @param string $field
     * @return int
     */
    public function max(string $field): int
    {
        return $this->model->max($field);
    }

    /** min
     * Notes:
     * User: cc
     * Date: 2020/9/22
     * Time: 1:35 下午
     * @param string $field
     * @return int
     */
    public function min(string $field): int
    {
        return $this->model->min($field);
    }

    /**
     * Notes: count
     * User: cc
     * Date: 2020/9/22
     * Time: 1:36 下午
     * @param string $field
     * @return int
     */
    public function count(string $field): int
    {
        return $this->model->count($field);
    }

    /**
     * Notes: avg
     * User: cc
     * Date: 2020/9/22
     * Time: 1:39 下午
     * @param string $field
     * @return int
     */
    public function avg(string $field): int
    {
        return $this->model->avg($field);
    }

    /**
     * Notes: whereNull
     * User: cc
     * Date: 2020/9/22
     * Time: 1:47 下午
     * @param string $field
     * @param string[] $columns
     * @return mixed
     */
    public function whereNull(string $field, $columns = array('*'))
    {
        return $this->model->whereNull($field)->select($columns)->get();
    }

    /**
     * Notes: whereNotNull
     * User: cc
     * Date: 2020/9/22
     * Time: 1:47 下午
     * @param string $field
     * @param string[] $columns
     * @return mixed
     */
    public function whereNotNull(string $field, $columns = array('*'))
    {
        return $this->model->whereNotNull($field)->select($columns)->get();
    }

    /**
     * Notes: getModel
     * User: clj
     * Date: 2020/9/21
     * Time: 8:44 上午
     * @return mixed
     */
    public function getModel() {
        return $this->model;
    }

}

定义一个子类继承上面的抽象类 (一个子类对应一个model模型)

<?php
namespace App\Repository;

use App\Model\UserModel;  // 引入对应的Model模型

class UserRepository extends AbstractRepository
{
    /**
     * User: clj
     * UserRepository constructor.
     * @param UserModel $userModel
     */

    public function __construct(UserModel $userModel)  // 依赖注入
    {
        $this->model = $userModel;
    }
}

在Services层里引入UserRepsotory(或者直接在控制器中引入,这里做了Services服务层,所以从Services层引入)

app/Services/UserService.php

<?php
namespace App\Services;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Tools\Automatic;
use Illuminate\Support\Facades\DB;
use App\Repository\UserRepository;
use App\Repository\UserApplicationRepository;

class UserService extends BaseService
{
    /**
     * 当前时间戳
     * currentDateTime
     */
    protected const currentDateTime = null;

    /**
     * @var UserRepository $userRepository
     */
    protected $userRepository;

    /**
     * @var UserApplicationRepository $userApplicationRepository
     */
    protected $userApplicationRepository;

    /***
     * UserService constructor.
     * @param UserRepository $userRepository
     * @param UserApplicationRepository $userApplicationRepository
     */
    public function __construct(
        UserRepository $userRepository,
        UserApplicationRepository $userApplicationRepository
    )
    {
        $this->userRepository = $userRepository;
        $this->userApplicationRepository = $userApplicationRepository;
    }

    /**
     * Notes: 登录
     * User: clj
     * Date: 2020/9/18
     * Time: 6:36 下午
     * @param array $params
     * @return array
     */
    public function loginService(array $params)
    {
        $user = $this->userRepository->findBy('phone',$params['phone']);
        if (empty($user)) {
            return $this->customError('账号不存在');
        }
        if (!Hash::check($params['password'], $user->password)) {
            return $this->customError('密码错误');
        }
        if (!$token = Auth::login($user)) {
            $this->customError('系统错误,无法生成令牌');
        } else {
            $data = [
                'access_token' => $token,
            ];
            return $this->customFormat($data);
        }
    }

    /**
     * Notes: 退出
     * User: clj
     * Date: 2020/9/18
     * Time: 6:36 下午
     * @return array
     */
    public function logoutService()
    {
        Auth::logout();
        return $this->customFormat('退出成功');
    }

    /**
     * Notes: 刷新
     * User: clj
     * Date: 2020/9/18
     * Time: 6:36 下午
     * @return array
     */
    public function refreshService()
    {
        if (!$token = Auth::refresh(true, true)) {
            return $this->customError(['msg' => '系统错误,无法生成令牌']);
        } else {
            $data = [
                'access_token' => $token,
            ];
            return $this->customFormat($data);
        }
    }

    /**
     * Notes: 获取用户token
     * User: clj
     * Date: 2020/9/18
     * Time: 6:36 下午
     * @return array
     */
    public function getUserTokenService()
    {
        return $this->customFormat(Auth::user());
    }

    /**
     * Notes: 注册
     * User: clj
     * Date: 2020/9/18
     * Time: 6:36 下午
     * @param array $userInfo
     * @return array
     */
    public function registerService(array $userInfo)
    {
        $userInfo['password'] = Hash::make($userInfo['password']);
        $userInfo['userInfoId'] = Automatic::automaticGenerated(4);
        $userInfo['name'] = Automatic::automaticGenerated(1);
        $userInfo['ip'] = getIp();
        $application['appId'] = Automatic::automaticGenerated(2);
        $application['appSecret'] = Automatic::automaticGenerated(3);
        $application['userInfoId'] = $userInfo['userInfoId'];
        $userExists = $this->userRepository->findBy('phone',$userInfo['phone']);
        if ($userExists) {
            return $this->customError('已注册,请直接登录');
        }
        DB::beginTransaction();
        try {
            $user = $this->userRepository->create($userInfo);
            $this->userApplicationRepository->create($application);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->customError($e->getMessage());
        }
        if (!$token = Auth::login($user)) {
            return $this->customError('系统错误,无法生成令牌');
        } else {
            $data = [
                'access_token' => $token,
            ];
            return $this->customFormat($data);
        }
    }

}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注