EntityManager.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * Pimf
  4. *
  5. * @copyright Copyright (c) Gjero Krsteski (http://krsteski.de)
  6. * @license http://krsteski.de/new-bsd-license New BSD License
  7. */
  8. namespace Pimf;
  9. use Pimf\DataMapper\Base;
  10. /**
  11. * Based on PDO it is a general manager for data persistence and object relational mapping.
  12. *
  13. * @package Pimf
  14. * @author Gjero Krsteski <[email protected]>
  15. *
  16. */
  17. class EntityManager extends Base
  18. {
  19. /**
  20. * @var string The namespace name of data-mappers repository.
  21. */
  22. protected $prefix;
  23. /**
  24. * @param \PDO $pdo
  25. * @param string $prefix The data-mappers repository name.
  26. */
  27. public function __construct(\PDO $pdo, $prefix = '\Pimf')
  28. {
  29. parent::__construct($pdo);
  30. $this->prefix = $prefix . '\DataMapper\\';
  31. }
  32. /**
  33. * @param string $entity The name of the data-mapper class.
  34. *
  35. * @return Base
  36. * @throws \BadMethodCallException If no entity fount at the repository.
  37. */
  38. public function load($entity)
  39. {
  40. $entity = $this->prefix . ucfirst($entity);
  41. if (true === $this->identityMap->hasId($entity)) {
  42. return $this->identityMap->getObject($entity);
  43. }
  44. if (!class_exists($entity)) {
  45. throw new \BadMethodCallException('entity "' . $entity . '" not found at the data-mapper repository');
  46. }
  47. $model = new $entity($this->pdo);
  48. $this->identityMap->set($entity, $model);
  49. return $this->identityMap->getObject($entity);
  50. }
  51. /**
  52. * @return bool
  53. */
  54. public function beginTransaction()
  55. {
  56. return $this->pdo->beginTransaction();
  57. }
  58. /**
  59. * @return bool
  60. */
  61. public function commitTransaction()
  62. {
  63. return $this->pdo->commit();
  64. }
  65. /**
  66. * @return bool
  67. */
  68. public function rollbackTransaction()
  69. {
  70. return $this->pdo->rollBack();
  71. }
  72. /**
  73. * @param string $entity
  74. *
  75. * @return Base
  76. */
  77. public function __get($entity)
  78. {
  79. return $this->load($entity);
  80. }
  81. /**
  82. * @return Database
  83. */
  84. public function getPDO()
  85. {
  86. return $this->pdo;
  87. }
  88. }