php-arsenal/doctrine-odm-transactional-document-manager

该软件包已被 废弃 并不再维护。没有建议替代软件包。

0.1.1 2021-07-06 11:27 UTC

This package is auto-updated.

Last update: 2023-03-07 23:36:18 UTC


README

基于 Maciej 的博客文章构建

Release CI Packagist

安装

使用 Composer 安装

composer require php-arsenal/doctrine-odm-transactional-document-manager 

添加到 services.yaml

    PhpArsenal\DoctrineOdmTransactionalDocumentManager\TransactionalDocumentManager:
        autowire: true
        autoconfigure: true

使用

我们还可以将那个 publishProducts() 代码包裹在一个 try-catch 块中,并在其 catch 部分调用 $this->documentManager->abortTransaction();,但如果事务未提交,它将自动回滚,因此这里实际上并不需要这样做。

<?php

namespace YourNamespace;

use PhpArsenal\DoctrineOdmTransactionalDocumentManager\TransactionalDocumentManager;

class ProductManager
{
    public function __construct(
        private TransactionalDocumentManager $documentManager, 
        private ProductRepository $productRepository
    ) {
    }
 
    public function publishProducts(): void
    {
        $products = $this->productRepository->findBy(['published' => false]);
 
        $this->documentManager->startTransaction();
 
        foreach ($products as $product) {
            $product->setPublished(true);
        }
 
        $this->documentManager->flush([
            'session' => $this->documentManager->getSession(),
        ]);
 
        $this->documentManager->commitTransaction();
    }
}