您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

103 行
2.9KB

  1. <?php
  2. namespace Lc\SovBundle\Doctrine;
  3. use Doctrine\ORM\EntityManager as DoctrineEntityManager;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Lc\SovBundle\Event\EntityManager\EntityManagerEvent;
  6. use Lc\SovBundle\Doctrine\EntityInterface;
  7. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  8. /**
  9. * class EntityManager.
  10. *
  11. * @author Simon Vieille <simon@deblan.fr>
  12. */
  13. class EntityManager
  14. {
  15. protected EventDispatcherInterface $eventDispatcher;
  16. protected DoctrineEntityManager $entityManager;
  17. public function __construct(EventDispatcherInterface $eventDispatcher, EntityManagerInterface $entityManager)
  18. {
  19. $this->eventDispatcher = $eventDispatcher;
  20. $this->entityManager = $entityManager;
  21. }
  22. public function getRepository($className)
  23. {
  24. return $this->entityManager->getRepository($this->getEntityName($className));
  25. }
  26. public function new($className)
  27. {
  28. $entityName = $this->getEntityName($className);
  29. return new $entityName;
  30. }
  31. public function create(EntityInterface $entity): self
  32. {
  33. $this->persist($entity);
  34. $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::CREATE_EVENT);
  35. return $this;
  36. }
  37. public function update(EntityInterface $entity): self
  38. {
  39. $this->persist($entity);
  40. $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::UPDATE_EVENT);
  41. return $this;
  42. }
  43. public function delete(EntityInterface $entity): self
  44. {
  45. $this->remove($entity);
  46. $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::DELETE_EVENT);
  47. return $this;
  48. }
  49. public function flush(): self
  50. {
  51. $this->entityManager->flush();
  52. return $this;
  53. }
  54. public function clear(): self
  55. {
  56. $this->entityManager->clear();
  57. return $this;
  58. }
  59. public function refresh(EntityInterface $entity): self
  60. {
  61. $this->entityManager->refresh($entity);
  62. return $this;
  63. }
  64. protected function persist(EntityInterface $entity)
  65. {
  66. $this->entityManager->persist($entity);
  67. }
  68. public function getClassMetadata($className){
  69. return $this->entityManager->getClassMetadata($className);
  70. }
  71. public function getEntityName($className)
  72. {
  73. if (substr($className, -9) === 'Interface') {
  74. return $this->entityManager->getClassMetadata($className)->getName();
  75. }else{
  76. return $className;
  77. }
  78. }
  79. }