Skip to content
This repository has been archived by the owner on Mar 7, 2023. It is now read-only.

Latest commit

 

History

History
61 lines (43 loc) · 2.11 KB

File metadata and controls

61 lines (43 loc) · 2.11 KB

Doctrine ODM Transactional Document Manager

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