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

This package is abandoned and no longer maintained. No replacement package was suggested.

0.1.1 2021-07-06 11:27 UTC

This package is auto-updated.

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


README

Built upon Maciej blog post

Release CI Packagist

Install

Require with Composer

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

Add to services.yaml

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

Use

We might also wrap that publishProducts() code in a try-catch block and call $this->documentManager->abortTransaction(); in its catch section, but if a transaction is not committed, it will be automatically aborted (rolled back), so there is no real need for that here.

<?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();
    }
}