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

92 行
2.6KB

  1. <?php
  2. namespace Lc\AdminBundle\Manager;
  3. use Doctrine\ORM\EntityManager as DoctrineEntityManager;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Lc\AdminBundle\Event\EntityManager\EntityManagerEvent;
  6. use Lc\AdminBundle\IModel\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. protected function persist(EntityInterface $entity)
  60. {
  61. $this->entityManager->persist($entity);
  62. }
  63. public function getEntityName($className)
  64. {
  65. if (substr($className, -9) === 'Interface') {
  66. return $this->entityManager->getClassMetadata($className)->getName();
  67. }else{
  68. return $className;
  69. }
  70. }
  71. }