DASPRiD / container-interop-doctrine

Doctrine factories for container-interop
107 stars 25 forks source link

[Feature] Http Transaction Middleware #37

Closed azjezz closed 4 years ago

azjezz commented 6 years ago

i intend to follow this up with a pull request.

i don't know if this should belong to this package, but would you be interested in a doctrine transaction middleware implementation ? it should be easy to do.

this is an example of a transaction middleware i have been using :

( i was inspired by the symfony/doctrine-bridge messenger middleware - https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Doctrine/Messenger/DoctrineTransactionMiddleware.php )

use Doctrine\ORM\EntityManager;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Throwable;

class DoctrineTransactionMiddleware implements MiddlewareInterface
{
    /** @var EntityManager $entityManager */
    protected $entityManager;

    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * @param ServerRequestInterface  $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     *
     * @throws Throwable
     * @throws \Doctrine\DBAL\ConnectionException
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
    {
        $this->entityManager->getConnection()->beginTransaction();

        try {
            $response = $handler->handle($request);
            $this->entityManager->flush();
            $this->entityManager->getConnection()->commit();
        } catch (Throwable $e) {
            $this->entityManager->getConnection()->rollBack();
            throw $e;
        }

        return $response;
    }
}
azjezz commented 6 years ago

ping @DASPRiD and @asgrim

asgrim commented 6 years ago

Personally, whilst I can see this could be useful (nice! :+1:), I don't think this package is the right place for this (the single concern is to wire Doctrine into a Psr\Container\ContainerInterface with factories), but as it's @DASPRiD 's package it's really up to him :)

DASPRiD commented 4 years ago

@asgrim agreed

asgrim commented 4 years ago

This repository is now deprecated. If you are still experiencing this issue, please feel free to open a new issue at https://github.com/Roave/psr-container-doctrine/issues - thanks!