Skip to content

Instantly share code, notes, and snippets.

@AntonioCS
Created January 10, 2022 14:56
Show Gist options
  • Save AntonioCS/1d932e8c042f27e924640bc828d5256e to your computer and use it in GitHub Desktop.
Save AntonioCS/1d932e8c042f27e924640bc828d5256e to your computer and use it in GitHub Desktop.
A trait for symfony to simplify adding the EntityManager to a class
<?php
declare(strict_types=1);
namespace App\Traits;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ObjectRepository;
trait HasEntityManager
{
private ?EntityManagerInterface $entityManager = null;
/**
* @required
*/
public function setEntityManger(EntityManagerInterface $entityManager) : static
{
$this->entityManager = $entityManager;
return $this;
}
public function getEntityManager() : EntityManagerInterface
{
return $this->entityManager;
}
private function emPersist(object $object) : static
{
$this->getEntityManager()->persist($object);
return $this;
}
private function emFlush() : static
{
$this->getEntityManager()->flush();
return $this;
}
private function emPersistAndFlush(object $object) : static
{
return $this->emPersist($object)
->emFlush();
}
private function emGetRepository(string $className) : ObjectRepository
{
return $this->getEntityManager()->getRepository($className);
}
private function emFindOneBy(string $className, array $criteria) : ?object
{
return $this->emGetRepository($className)->findOneBy($criteria);
}
private function emFindOneByOrThrow(string $className, array $criteria, string $throwMessage = 'Unable to find results') : object
{
$res = $this->emFindOneBy($className, $criteria);
if ($res === null) {
throw new \RuntimeException($throwMessage);
}
return $res;
}
private function emFindBy(string $className, array $criteria) : array
{
return $this->emGetRepository($className)->findBy($criteria);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment