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();
相关推荐
stand_forever17 小时前
laravel框架优化
php·laravel
Python涛哥19 小时前
PHP框架之Laravel框架教程:1. laravel搭建
开发语言·php·laravel
~央千澈~6 天前
Laravel 系统版本查看及artisan管理员密码找回方法针对各个版本通用方法及原理-优雅草卓伊凡
php·laravel
小小怪下士yeah6 天前
Laravel 静态方法的合理使用考量【超详细】
android·java·laravel
Rocket MAN7 天前
Laravel 原子锁概念讲解
php·wpf·laravel
ONLYOFFICE10 天前
如何将 ONLYOFFICE 文档集成到使用 Laravel 框架编写的 PHP 网络应用程序中
php·laravel
四季豆豆豆14 天前
博客项目 laravel vue mysql 第四章 分类功能
vue.js·mysql·laravel
yanwushu22 天前
10分钟搭建 PHP 开发环境教程
php·laravel
RainSerein24 天前
Laravel8中使用phpword生成word文档
word·php·laravel
RainSerein24 天前
Laravel8中调取腾讯云文字识别OCR
ocr·php·腾讯云·laravel