• Laravel一些优雅的写法


    目录

    1. 新增商品操作

    2. 修改商品操作


    1. 新增商品操作

    1. // 原则,所有服务类只有一个public入口,或者多个public入口,但是他们做都是同一件事情
    2. Class CreateService {
    3. // 创建类的入口, 根据dto去新建
    4. public function create(Dto $dto){
    5. $user = User::find($dto->getUserId());
    6. // 这里做一些系列的参数验证,此处省略...
    7. // 先构建商品model对象, 不要在事务期间构建,减少事务等待
    8. $good = $this->buildGood($user, $dto);
    9. // 构建商品的属性(一对多)
    10. $good->setRelation('attributes', $this->buildAttributes($dto));
    11. // 构建商品的活动(一对多)
    12. $good->setRelation('activities', $this->buildActivities($dto));
    13. DB::transaction(function () use (
    14. $good
    15. ) {
    16. // 保存商品model对象
    17. // 主表
    18. $good->save();
    19. // 批量插入商品属性表
    20. $good->attributes()->saveMany(
    21. $good->attributes->all()
    22. );
    23. // 批量插入商品活动表
    24. $good->activities()->saveMany(
    25. $good->activities->all()
    26. );
    27. // 触发商品新增事件,要delay延迟事件,确保事务提交后触发
    28. delay_event(new GoodCreated());
    29. });
    30. }
    31. // 根据Good类去新建
    32. public function createByGood(Good $good) {
    33. // ....
    34. }
    35. /** 构建商品属性对象
    36. * @param Dto $dto
    37. * @return Collection
    38. */
    39. protected function buildAttributes(
    40. Dto $dto
    41. ): Collection {
    42. $newCollection = new Collection();
    43. // 获取页面提交的属性名称列表
    44. $$list = $dto->getAttributes();
    45. if (empty($list)) {
    46. return $newCollection;
    47. }
    48. foreach ($list as $name) {
    49. $newCollection->add(new GoodAttribute([
    50. 'name' => $name,
    51. ]));
    52. }
    53. return $newCollection;
    54. }
    55. // 构建商品活动对象
    56. protected function buildActivities(
    57. Dto $dto
    58. ): Collection {
    59. $newCollection = new Collection();
    60. if (!empty($dto->getAtivityId())) {
    61. $newCollection->add(
    62. new GoodActivity(
    63. [
    64. 'activity_id' => $dto->getAtivityId(),
    65. ]
    66. )
    67. );
    68. }
    69. return $newCollection;
    70. }
    71. /** 构建商品对象
    72. * @param User $user
    73. * @param Dto $dto
    74. * @return Good
    75. */
    76. protected function buildGood(
    77. User $user,
    78. Dto $dto
    79. ): Good {
    80. return new Good([
    81. 'updated_at' => $dto->getDataUpdatedAt(),
    82. 'user_id' => $user->id,
    83. 'user_name' => $user->username,
    84. ]);
    85. }
    86. }
    87. class Dto
    88. {
    89. protected $attributes;
    90. protected $dataUpdatedAt;
    91. protected $activityId;
    92. protected $userId;
    93. public static function build(array $params): Dto {
    94. $self = new self();
    95. $self->attributes = (array)($params['attributes'] ?? []);
    96. $self->dataUpdatedAt = Carbon::now()->toDatetimeString();
    97. $self->activityId = intval($params['activity_id'] ?? 0);
    98. $self->userId = intval($params['user_id'] ?? 0);
    99. return $self;
    100. }
    101. }
    102. // controller
    103. GoodController {
    104. // 商品新增执行入口
    105. public function create(Request $request, CreateService $createService): array {
    106. $service->create(
    107. Dto::build($request->validated())
    108. );
    109. return ['code' => 200];
    110. }
    111. }

    2. 修改商品操作

    1. // 原则,所有服务类只有一个public入口,或者多个public入口,但是他们做都是同一件事情
    2. Class UpdateService {
    3. // 创建类的入口, 根据dto去新建
    4. public function update(Dto $dto){
    5. $good = Good::find($dto->getGoodId());
    6. $good->loadMissing([
    7. 'attributes',
    8. 'activities',
    9. ]);
    10. $user = User::find($dto->getUserId());
    11. // 这里做一些系列的参数验证,此处省略...
    12. // 先构建商品model对象, 不要在事务期间构建,减少事务等待
    13. $good = $this->buildGood($good, $user, $dto);
    14. // 构建商品的属性(一对多)
    15. $good->setRelation('attributes', $this->buildAttributes($good, $dto));
    16. // 构建商品的活动(一对多)
    17. $good->setRelation('activities', $this->buildActivities($good, $dto));
    18. DB::transaction(function () use (
    19. $good
    20. ) {
    21. // 保存商品model对象
    22. // 主表
    23. $good->save();
    24. // 批量插入商品属性表
    25. $good->attributes()->saveMany(
    26. $good->attributes->all()
    27. );
    28. // 删除没选中的商品属性
    29. $good->attributes()->whereNotIn(
    30. 'id',
    31. $good->attributes->pluck('id')->filter()->unique()->all()
    32. )->delete();
    33. // 批量插入商品活动表
    34. $good->activities()->saveMany(
    35. $good->activities->all()
    36. );
    37. // 删除没选中的商品活动
    38. $good->activities->whereNotIn(
    39. 'id',
    40. $good->activities->pluck('id')->filter()->unique()->all()
    41. );
    42. // 触发商品修改事件,要delay延迟事件,确保事务提交后触发
    43. delay_event(new GoodUpdated());
    44. });
    45. }
    46. // 根据product类去新建
    47. public function updateByGood(Good $product, array $params) {
    48. }
    49. /** 构建商品属性对象
    50. * @param Dto $dto
    51. * @return Collection
    52. */
    53. protected function buildAttributes(
    54. Good $good,
    55. Dto $dto
    56. ): Collection {
    57. $newCollection = new Collection();
    58. // 获取页面提交的属性名称列表
    59. $list = $dto->getAttributes();
    60. if (empty($list)) {
    61. return $newCollection;
    62. }
    63. $oldAttributes = $good->attributes->keyBy('name');
    64. foreach ($list as $name) {
    65. // 按商品属性名字取查找,如果已经添加,就不需要新建了
    66. if ($attribute = $oldAttributes->get($name)) {
    67. $newCollection->add($attribute);
    68. } else {
    69. // 没有添加,则新建
    70. $newCollection->add(new GoodAttribute([
    71. 'name' => $name,
    72. ]));
    73. }
    74. }
    75. return $newCollection;
    76. }
    77. // 构建商品活动对象
    78. protected function buildActivities(
    79. Good $good,
    80. Dto $dto
    81. ): Collection {
    82. $newCollection = new Collection();
    83. $oldActivities = $good->activities->keyBy('activity_id');
    84. if (empty($dto->getAtivityId())) {
    85. return $newCollection;
    86. }
    87. if ($activity = $oldActivities->get($dto->getAtivityId())) {
    88. // 已经添加过活动,就无需再新增
    89. $newCollection->add($activity);
    90. } else {
    91. // 新增活动
    92. $newCollection->add(
    93. new GoodActivity(
    94. [
    95. 'activity_id' => $dto->getAtivityId(),
    96. ]
    97. )
    98. );
    99. }
    100. return $newCollection;
    101. }
    102. /** 构建商品对象
    103. * @param User $user
    104. * @param Dto $dto
    105. * @return Good
    106. */
    107. protected function buildGood(
    108. Good $good,
    109. User $user,
    110. Dto $dto
    111. ): Good {
    112. return $good->fill([
    113. 'updated_at' => $dto->getDataUpdatedAt(),
    114. 'user_id' => $user->id,
    115. 'user_name' => $user->username,
    116. ]);
    117. }
    118. }
    119. class Dto
    120. {
    121. protected $attributes;
    122. protected $dataUpdatedAt;
    123. protected $activityId;
    124. protected $userId;
    125. protected $goodId;
    126. public static function build(array $params): Dto {
    127. $self = new self();
    128. $self->attributes = (array)($params['attributes'] ?? []);
    129. $self->dataUpdatedAt = Carbon::now()->toDatetimeString();
    130. $self->activityId = intval($params['activity_id'] ?? 0);
    131. $self->userId = intval($params['user_id'] ?? 0);
    132. $self->goodId = intval($params['good_id'] ?? 0);
    133. return $self;
    134. }
    135. // ...一下实现获取属性值的方法,此处省略
    136. }
    137. // controller
    138. class GoodController {
    139. // 商品修改执行入口
    140. public function update(Request $request, UpdateService $updateService): array {
    141. $service->update(
    142. Dto::build($request->validated())
    143. );
    144. return ['code' => 200];
    145. }
    146. }

  • 相关阅读:
    七天速通javaSE:第四天 数组进阶
    DSPE-PEG-TAT,磷脂-聚乙二醇-靶向穿膜肽TAT,一种磷脂PEG肽
    复合查询与过滤查询的区别,记ElasticSearch检索时踩过的”坑“!
    如何部署lvs负载均衡集群 DR模式
    数字化转型重塑企业竞争优势,SaaS电商系统助力锂电池行业实现降本增效
    基于SSM养老院管理系统毕业设计-附源码221609
    kubeadm安装kubernetes
    苏宁api接口
    十天学前端之JS篇(六)
    分库分表总结
  • 原文地址:https://blog.csdn.net/zhazhaji/article/details/133146224