Created
October 29, 2019 18:58
-
-
Save dominikzogg/e97c3a73922cb0fa58ea52e448d73cbf to your computer and use it in GitHub Desktop.
EntityManager within Swoole
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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() | |
); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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