Setup 安装

辅助 Hyperf 快速集成 CURD API 的工具集,首先需要安装依赖库 kain/hyperf-curd

  1. composer require kain/hyperf-curd

config/autoload/dependencies.php 内完成关系配置

  1. return [
  2. Hyperf\Curd\CurdInterface::class => Hyperf\Curd\CurdService::class,
  3. ];

可以定义一个顶层抽象类注入依赖,例如

  1. use Hyperf\Curd\CurdInterface;
  2. use Hyperf\Di\Annotation\Inject;
  3. use Hyperf\Extra\Hash\HashInterface;
  4. use Hyperf\Extra\Token\TokenInterface;
  5. use Hyperf\Extra\Utils\UtilsInterface;
  6. use Hyperf\HttpServer\Contract\RequestInterface;
  7. use Hyperf\HttpServer\Contract\ResponseInterface;
  8. use Hyperf\Validation\Contract\ValidatorFactoryInterface;
  9. abstract class BaseController
  10. {
  11. /
  12. * @Inject()
  13. * @var RequestInterface
  14. */
  15. protected RequestInterface $request;
  16. /
  17. * @Inject()
  18. * @var ResponseInterface
  19. */
  20. protected ResponseInterface $response;
  21. /
  22. * @Inject()
  23. * @var ValidatorFactoryInterface
  24. */
  25. protected ValidatorFactoryInterface $validation;
  26. /
  27. * @Inject()
  28. * @var CurdInterface
  29. */
  30. protected CurdInterface $curd;
  31. /
  32. * @Inject()
  33. * @var HashInterface
  34. */
  35. protected HashInterface $hash;
  36. /
  37. * @Inject()
  38. * @var TokenInterface
  39. */
  40. protected TokenInterface $token;
  41. /
  42. * @Inject()
  43. * @var UtilsInterface
  44. */
  45. protected UtilsInterface $utils;
  46. }

Builder 构造器

构造器是 CURD 的组装器,按需要可灵活组合成想要的逻辑

验证请求并返回数据

  • should(array CURD - 图1extend): array

    • rule array 验证规则
    • extend array 扩展验证规则

例如,验证某个接口:

  1. public function bulkAdd(): array
  2. {
  3. $body = $this->curd->should([
  4. 'type_id' => 'required',
  5. 'data' => 'required|array',
  6. 'data.*.name' => 'required',
  7. 'data.*.url' => 'required'
  8. ]);
  9. return [
  10. 'error' => 0,
  11. 'msg' => 'ok'
  12. ];
  13. }

计划 curd 工厂

  • model(string $name, array $body): CurdFactory

    • name string 模型名称
    • body array 请求数据
    • CurdFactory

      • where(array $value) 设置条件

        • value array 条件数组
      • query(Closure $value) 设置子查询

        • value Closure 闭包子查询,例如 function ($query) {}
      • orderBy(array $value) 设置排序

        • value array 排序数组,例如 ['create_time' => 'desc']
      • select(array $value) 设置字段

        • value array 字段数组
      • autoTimestamp(bool $value, ?string $createAt = null, ?string $updateAt = null) 设置自动生成时间戳

        • value bool 是否开启
        • createAt string 创建时间字段
        • updateAt string 更新时间字段
      • afterHook(Closure $value) 后置周期

        • value Closure 闭包函数,例如 function ($param) {}
      • prepHook(Closure $value) 事务预处理周期

        • value Closure 闭包函数,例如 function ($param) {}
      • originLists() array 获取列表数据
      • lists() array 获取分页数据
      • get() array 获取数据
      • add() array 新增数据
      • edit() array 编辑数据
      • delete() array 删除数据

工厂最终包含了 originLists() lists() get() add() edit() delete() 执行输出方式,例如:

  1. // 示例
  2. $body = $this->curd->should([
  3. ...
  4. ]);
  5. $this->curd->model('acl', $body)
  6. ->where([
  7. ['status', '=', 1]
  8. ])
  9. ->select(['id', 'name'])
  10. ->orderBy(['create_time' => 'desc'])
  11. ->originLists();
  12. // 示例
  13. $body = $this->curd->should([
  14. ...
  15. ]);
  16. $this->curd->model('acl', $body)
  17. ->afterHook(function (stdClass $param) {
  18. // $param->id 是 insertId
  19. Db::table('some_rel')->insert([
  20. 'aid' => $param->id
  21. ]);
  22. return true;
  23. })
  24. ->add();

不同的执行输出不包含完整的构造子句

是否支持 originLists lists get add edit delete
where
query
orderBy
select
autoTimestamp
afterHook
prepHook

Common 通用特征

通用特征可以快速生产 CURD 接口类,这需要继承抽象类 CurdController ,其中包含一些静态属性需要在单例中重写(注意:属性重写定义需当成常量,存在变量逻辑会受协程影响),你可以使用原顶层抽象继承它:

  1. use Hyperf\Curd\CurdController;
  2. use Hyperf\Curd\CurdInterface;
  3. use Hyperf\Di\Annotation\Inject;
  4. use Hyperf\Extra\Hash\HashInterface;
  5. use Hyperf\Extra\Token\TokenInterface;
  6. use Hyperf\Extra\Utils\UtilsInterface;
  7. use Hyperf\HttpServer\Contract\RequestInterface;
  8. use Hyperf\HttpServer\Contract\ResponseInterface;
  9. use Hyperf\Validation\Contract\ValidatorFactoryInterface;
  10. abstract class BaseController extends CurdController
  11. {
  12. /
  13. * @Inject()
  14. * @var RequestInterface
  15. */
  16. protected RequestInterface $request;
  17. /
  18. * @Inject()
  19. * @var ResponseInterface
  20. */
  21. protected ResponseInterface $response;
  22. /
  23. * @Inject()
  24. * @var ValidatorFactoryInterface
  25. */
  26. protected ValidatorFactoryInterface $validation;
  27. /
  28. * @Inject()
  29. * @var CurdInterface
  30. */
  31. protected CurdInterface $curd;
  32. /
  33. * @Inject()
  34. * @var HashInterface
  35. */
  36. protected HashInterface $hash;
  37. /
  38. * @Inject()
  39. * @var TokenInterface
  40. */
  41. protected TokenInterface $token;
  42. /
  43. * @Inject()
  44. * @var UtilsInterface
  45. */
  46. protected UtilsInterface $utils;
  47. }

使用示例

AclController 为例,其中完整使用到 OriginListsModel ListsModel GetModel AddModel EditModel DeleteModel

  1. use App\RedisModel\System\AclRedis;
  2. use App\RedisModel\System\RoleRedis;
  3. use Hyperf\Curd\Common\AddModel;
  4. use Hyperf\Curd\Common\DeleteModel;
  5. use Hyperf\Curd\Common\EditModel;
  6. use Hyperf\Curd\Common\GetModel;
  7. use Hyperf\Curd\Common\ListsModel;
  8. use Hyperf\Curd\Common\OriginListsModel;
  9. use Hyperf\DbConnection\Db;
  10. use Hyperf\Di\Annotation\Inject;
  11. use stdClass;
  12. class AclController extends BaseController
  13. {
  14. use OriginListsModel, ListsModel, GetModel, AddModel, EditModel, DeleteModel;
  15. protected static string $model = 'acl';
  16. protected static array $addValidate = [
  17. 'name' => 'required|array',
  18. 'key' => 'required',
  19. 'write' => 'sometimes|array',
  20. 'read' => 'sometimes|array'
  21. ];
  22. protected static array $editValidate = [
  23. 'name' => 'required_if:switch,false|array',
  24. 'key' => 'required_if:switch,false',
  25. 'write' => 'sometimes|array',
  26. 'read' => 'sometimes|array'
  27. ];
  28. /
  29. * @Inject()
  30. * @var AclRedis
  31. */
  32. private AclRedis $aclRedis;
  33. /
  34. * @Inject()
  35. * @var RoleRedis
  36. */
  37. private RoleRedis $roleRedis;
  38. public function addBeforeHook(stdClass $ctx): bool
  39. {
  40. $this->before($ctx->body);
  41. return true;
  42. }
  43. public function addAfterHook(stdClass $ctx): bool
  44. {
  45. $this->clearRedis();
  46. return true;
  47. }
  48. public function editBeforeHook(stdClass $ctx): bool
  49. {
  50. if (!$ctx->switch) {
  51. $this->before($ctx->body);
  52. }
  53. return true;
  54. }
  55. public function editAfterHook(stdClass $ctx): bool
  56. {
  57. $this->clearRedis();
  58. return true;
  59. }
  60. private function before(array &$body): void
  61. {
  62. $body['name'] = json_encode($body['name'], JSON_UNESCAPED_UNICODE);
  63. $body['write'] = implode(',', (array)$body['write']);
  64. $body['read'] = implode(',', (array)$body['read']);
  65. }
  66. public function deleteAfterHook(stdClass $ctx): bool
  67. {
  68. $this->clearRedis();
  69. return true;
  70. }
  71. private function clearRedis(): void
  72. {
  73. $this->aclRedis->clear();
  74. $this->roleRedis->clear();
  75. }
  76. /
  77. * Exists Acl Key
  78. * @return array
  79. */
  80. public function validedKey(): array
  81. {
  82. $body = $this->request->post();
  83. if (empty($body['key'])) {
  84. return [
  85. 'error' => 1,
  86. 'msg' => 'require key'
  87. ];
  88. }
  89. $exists = Db::table('acl')
  90. ->where('key', '=', $body['key'])
  91. ->exists();
  92. return [
  93. 'error' => 0,
  94. 'data' => $exists
  95. ];
  96. }
  97. }

OriginListsModel 列表查询

相关属性

  • model string 模型名称
  • originListsValidate array 列表验证
  • originListsCondition array 列表条件
  • originListsOrders array 列表排序,默认 ['create_time' => 'desc']
  • originListsField array 列表字段

相关方法

  • originListsConditionQuery(array $body) Closure 子查询

    • body array 请求数据
  • originListsCustomReturn(array $body, array $result) array 自定义返回

    • body array 请求数据
    • result array 返回结果

ListsModel 分页查询

相关属性

  • model string 模型名称
  • listsValidate array 分页验证
  • listsCondition array 分页条件
  • listsOrders array 分页排序,默认 ['create_time' => 'desc']
  • listsField array 分页字段

相关方法

  • listsConditionQuery(array $body) Closure 子查询

    • body array 请求数据
  • listsCustomReturn(array $body, array $result) array 自定义返回

    • body array 请求数据
    • result array 返回结果

Get 数据查询

相关属性

  • model string 模型名称
  • getValidate array 数据验证
  • getCondition array 数据条件
  • getOrders array 数据排序
  • getField array 数据字段

相关方法

  • getConditionQuery(array $body) Closure 子查询

    • body array 请求数据
  • getCustomReturn(array $body, array $result) array 自定义返回

    • body array 请求数据
    • result array 返回结果

Add 新增

相关属性

  • model string 模型名称
  • autoTimestamp bool 自动更新时间戳,默认自动生成 create_time update_time 的时间戳
  • addModel string 新增模型名称,重写后将替代 model
  • addValidate array 新增验证

相关方法

  • addBeforeHook(stdClass $ctx) bool 前置周期

    • ctx stdClass 上下文变量
  • addAfterHook(stdClass $ctx) bool 后置周期

    • ctx stdClass 上下文变量

Edit 修改

  • model string 模型名称
  • autoTimestamp bool 自动更新时间戳,默认自动更新 update_time 的时间戳
  • editModel string 编辑模型名称,重写后将替代 model
  • editValidate array 编辑验证
  • editCondition array 编辑条件

相关方法

  • editBeforeHook(stdClass $ctx) bool 前置周期

    • ctx stdClass 上下文变量
  • editAfterHook(stdClass $ctx) bool 后置周期

    • ctx stdClass 上下文变量

Delete 删除

  • model string 模型名称
  • deleteModel string 删除模型名称,重写后将替代 model
  • deleteValidate array 删除验证
  • deleteCondition array 删除条件

相关方法

  • deleteBeforeHook(stdClass $ctx) bool 前置周期

    • ctx stdClass 上下文变量
  • deletePrepHook(stdClass $ctx) bool 事务预处理周期

    • ctx stdClass 上下文变量
  • deleteAfterHook(stdClass $ctx) bool 后置周期

    • ctx stdClass 上下文变量