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();
相关推荐
暗冰ཏོ2 天前
PHP 全栈开发学习手册:从基础到高级实战、Laravel、Redis、面试题完整版
学习·php·laravel
ooseabiscuit8 天前
Laravel 1.x:揭秘PHP框架的起源与设计
php·laravel
ooseabiscuit8 天前
Laravel5
android·php·laravel
ooseabiscuit9 天前
Laravel 8.x核心特性深度解析
php·laravel
SuperherRo12 天前
服务攻防-开发框架安全&ThinkPHP&Laravel&SpringBoot&Struts2&SpringCloud&复现
spring boot·laravel·thinkphp·struts2·框架安全
JSON_L15 天前
Laravel-Admin 自定义删除完整实现
php·laravel·laravel-admin
JSON_L15 天前
Laravel-Admin 新增和编辑差异化显示
php·laravel·laravel-admin
zx28596340017 天前
Laravel 7.x新特性全解析
php·laravel
zx28596340017 天前
Laravel 4.x:颠覆PHP框架的10大革新特性
开发语言·php·laravel
xxjj998a17 天前
PHP vs C++:性能与用途全解析
php·laravel