Skip to content

Instantly share code, notes, and snippets.

@dominikzogg
Created October 29, 2019 18:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dominikzogg/e97c3a73922cb0fa58ea52e448d73cbf to your computer and use it in GitHub Desktop.
Save dominikzogg/e97c3a73922cb0fa58ea52e448d73cbf to your computer and use it in GitHub Desktop.
EntityManager within Swoole
<?php
declare(strict_types=1);
namespace App\Orm;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Decorator\EntityManagerDecorator as DoctrineEntityManagerDecorator;
use Doctrine\ORM\EntityManager;
class EntityManagerDecorator extends DoctrineEntityManagerDecorator
{
/**
* @return void
*/
public function restoreIfClosed(): void
{
if (false === $this->isOpen()) {
$this->restore();
}
}
/**
* @return void
*/
public function reconnectIfNotPinged(): void
{
$connection = $this->getConnection();
if (false === $connection->ping($connection)) {
$connection->close();
$connection->connect();
}
}
/**
* @return void
*/
private function restore(): void
{
$this->wrapped = EntityManager::create(
$this->wrapped->getConnection(),
$this->wrapped->getConfiguration(),
$this->wrapped->getEventManager()
);
}
}
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Orm\EntityManagerDecorator;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
final class EntityManagerMiddleware implements MiddlewareInterface
{
/**
* @var EntityManagerDecorator
*/
private $entityManagerDecorator;
/**
* @param EntityManagerDecorator $entityManagerDecorator
*/
public function __construct(EntityManagerDecorator $entityManagerDecorator)
{
$this->entityManagerDecorator = $entityManagerDecorator;
}
/**
* @param ServerRequestInterface $request
* @param PsrRequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, PsrRequestHandlerInterface $handler): ResponseInterface
{
$this->entityManagerDecorator->restoreIfClosed();
$this->entityManagerDecorator->reconnectIfNotPinged();
$response = $handler->handle($request);
$this->entityManagerDecorator->clear();
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment