Built upon Maciej blog post
Require with Composer
composer require php-arsenal/doctrine-odm-transactional-document-manager
Add to services.yaml
PhpArsenal\DoctrineOdmTransactionalDocumentManager\TransactionalDocumentManager:
autowire: true
autoconfigure: true
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();
}
}