PageRenderTime 41ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/Croogo/Model/Behavior/AliasableBehavior.php

https://github.com/kareypowell/croogo
PHP | 114 lines | 42 code | 12 blank | 60 comment | 2 complexity | ef442862af614d5d1c6bcf2bbc64a2e5 MD5 | raw file
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. /**
  4. * Aliasable Behavior
  5. *
  6. * Utility behavior to allow easy retrieval of records by id or its alias
  7. *
  8. * @package Croogo.Croogo.Model.Behavior
  9. * @since 1.4
  10. * @author Rachman Chavik <rchavik@xintesa.com>
  11. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  12. * @link http://www.croogo.org
  13. */
  14. class AliasableBehavior extends ModelBehavior {
  15. /**
  16. * _byIds
  17. *
  18. * @var array
  19. */
  20. protected $_byIds = array();
  21. /**
  22. * _byAlias
  23. *
  24. * @var array
  25. */
  26. protected $_byAlias = array();
  27. /**
  28. * setup
  29. *
  30. * @param Model $model
  31. * @param array $config
  32. * @return void
  33. */
  34. public function setup(Model $model, $config = array()) {
  35. $config = Hash::merge(array(
  36. 'id' => 'id',
  37. 'alias' => 'alias',
  38. ), $config);
  39. $this->settings[$model->alias] = $config;
  40. $this->reload($model);
  41. }
  42. /**
  43. * reload
  44. *
  45. * @param Model $model
  46. * @return void
  47. */
  48. public function reload(Model $model) {
  49. $config = $this->settings[$model->alias];
  50. $this->_byIds[$model->alias] = $model->find('list', array(
  51. 'fields' => array($config['id'], $config['alias']),
  52. 'conditions' => array(
  53. $model->alias . '.' . $config['alias'] . ' != ' => '',
  54. ),
  55. ));
  56. $this->_byAlias[$model->alias] = array_flip($this->_byIds[$model->alias]);
  57. }
  58. /**
  59. * byId
  60. *
  61. * @param Model $model
  62. * @param integer $id
  63. * @return boolean
  64. */
  65. public function byId(Model $model, $id) {
  66. if (!empty($this->_byIds[$model->alias][$id])) {
  67. return $this->_byIds[$model->alias][$id];
  68. }
  69. return false;
  70. }
  71. /**
  72. * byAlias
  73. *
  74. * @param Model $model
  75. * @param string $alias
  76. * @return boolean
  77. */
  78. public function byAlias(Model $model, $alias) {
  79. if (!empty($this->_byAlias[$model->alias][$alias])) {
  80. return $this->_byAlias[$model->alias][$alias];
  81. }
  82. return false;
  83. }
  84. /**
  85. * listById
  86. *
  87. * @param Model $model
  88. * @return string
  89. */
  90. public function listById(Model $model) {
  91. return $this->_byIds[$model->alias];
  92. }
  93. /**
  94. * listByAlias
  95. *
  96. * @param Model $model
  97. * @return string
  98. */
  99. public function listByAlias(Model $model) {
  100. return $this->_byAlias[$model->alias];
  101. }
  102. }