Laravel一些优雅的写法

  1. 新增操作
php 复制代码
// 原则,所有服务类只有一个public入口,或者多个public入口,但是他们做都是同一件事情
Class CreateService {


    // 创建类的入口, 根据dto去新建
    public function create(Dto $dto){

        // 先构建model对象, 不要在事务期间构建,减少事务等待
        $good = $this->buildGood($designProduct, $dto);
            $good->setRelation('aList', $this->buildAList($dto));
            $good->setRelation('bList', $this->buildBList($dto));


    DB::transaction(function () use (
            $good
        ) {

             // 保存model对象
               // 主表
                $good->save();
                // 主表关联其他表
                $good->aList()->saveMany(
                    $designReference->aList->all()
                );
                // 主表关联其他表
                $good->bList()->saveMany(
                    $designReference->bList->all()
                );
            // 触发事件,要delay延迟事件,确保事务提交后触发
            delay_event(new GoodCreated());
        });

    }


    // 根据product类去新建
    public function createByProduct(Product $product) {
        // build reference
        // save()
   }


    /**
     * @param Dto $dto
     * @return Collection
     */
    protected function buildAList(
        Dto $dto
    ): Collection {
        $newCollection  = new Collection();
        $$list = array_filter_unique(explode(',', $dto->getName()));

        if (empty($list)) {
            return $newCollection;
        }

        foreach ($list as $name) {
            $newCollection->add(new GoodAList([
                'name'    => $name,
            ]));
        }

        return $newCollection;
    }

    protected function buildBList(
        Dto $dto
    ): Collection {
        $newCollection  = new Collection();

        if (!empty($dto->getBName())) {
            $newCollection->add(
                new GoodBList(
                    [
                        'country_name'    => $dto->getBName(),
                    ]
                )
            );
        }

        return $newCollection;
    }


    /**
     * @param Product $product
     * @param Dto $dto
     * @return Good
     */
    protected function buildGood(
        Product $product,
        Dto $dto
    ): Good {
        return new Good([
          
            'updated_at'   => $dto->getDataUpdatedAt(),
            'band_id'   => $product->band_id,
        ]);
    }

}

$service = new CreateService();
$service->create();
相关推荐
86Eric1 天前
Laravel 使用 事件和监听器实现 数据状态变更
php·laravel·事件与监听器·队列监听器
hanzhuhuaa3 天前
win10 快速搭建 lnmp+swoole 环境 ,部署laravel6 与 swoole框架laravel-s项目2
后端·laravel·swoole
86Eric6 天前
Laravel Trait 实现 统一JSON 响应格式
laravel·trait·api统一响应
kkk162224520 天前
Laravel框架下通过DB获取数据并转为数组的方法
数据库·oracle·laravel
阳光照进我心窝20 天前
Laravel DB门面和Eloquent模型的查询及差异
laravel
HOOLOO24 天前
Docker部署Laravel项目
docker·laravel·php-fpm
道系女孩~1 个月前
laravel项目中使用FFMPeg 剪裁视频
php·laravel
斯密码赛我是美女1 个月前
laravel Blade 模板引擎
php·laravel
菜鸟码农_Shi1 个月前
Laravel 队列入门全攻略:从基础到实战
laravel
rorg1 个月前
搭建laravle 数字产品销售平台 php
php·laravel