ORM.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace PHPixie;
  3. /**
  4. * ORM Module for PHPixie
  5. *
  6. * This module allows you to instantly turn your tables
  7. * into Models and specify their relations in a simple way.
  8. *
  9. * @see \PHPixie\DB\Query
  10. * @package DB
  11. */
  12. class ORM {
  13. /**
  14. * Pixie Dependancy Container
  15. * @var \PHPixie\Pixie
  16. */
  17. public $pixie;
  18. /**
  19. * Cache of ORM tables columns
  20. * @var array
  21. */
  22. public $column_cache = array();
  23. /**
  24. * Initializes the ORM module
  25. *
  26. * @param \PHPixie\Pixie $pixie Pixie dependency container
  27. */
  28. public function __construct($pixie) {
  29. $this->pixie = $pixie;
  30. }
  31. /**
  32. * Initializes ORM model by name, and optionally fetches an item by id
  33. *
  34. * @param string $name Model name
  35. * @param mixed $id If set ORM will try to load the item with this id from the database
  36. * @return \PHPixie\ORM\Model ORM model, either empty or preloaded
  37. */
  38. public function get($name, $id = null)
  39. {
  40. $model = $this->pixie->app_namespace."Model\\".ucfirst($name);
  41. $model = new $model($this->pixie);
  42. if ($id != null)
  43. {
  44. $model = $model->where($model->id_field, $id)->find();
  45. $model->values(array($model->id_field => $id));
  46. }
  47. return $model;
  48. }
  49. /**
  50. * Initializes an ORM Result with which model to use and which result to
  51. * iterate over
  52. *
  53. * @param string $model Model name
  54. * @param \PHPixie\DB\Result $dbresult Database result
  55. * @param array $with Array of rules for preloaded relationships
  56. * @return \PHPixie\ORM\Result Initialized Result
  57. */
  58. public function result($model, $dbresult, $with = array()) {
  59. return new \PHPixie\ORM\Result($this->pixie, $model, $dbresult, $with);
  60. }
  61. /**
  62. * Initializes an ORM Model Extension.
  63. *
  64. * @param string $class Extension class name
  65. * @param \PHPixie\ORM\Model $model Associated Model
  66. * @return \PHPixie\ORM\Extension Initialized Extension
  67. */
  68. public function extension($class, $model) {
  69. return new $class($this->pixie, $model);
  70. }
  71. }