Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: ObjectConverter, czyli wyniki metod do tablicy.
Forum PHP.pl > Forum > PHP > Object-oriented programming
q3trm
Witam,

ostatnio dawno nie kodowałem w PHP właściwie większość czasu poświęcam JavaScript, dlatego postanowiłem napisać klasę(ObjectConverter) w celu poznania bliżej refleksji i odświeżenia umiejętności. Klasa ma na celu pobieranie wyników metod klasy podanej konwersji, metody są pobierane na podstawie członu nazwy np: wszystkie publiczne metody zaczynające się na "get" zostaną użyte do konwersji, po czym wynik zostanie zapisany do tablicy i zwrócony. Metody podczas konwersji mogą otrzymywać zewnętrznie parametry.

  1. <?php
  2.  
  3.  
  4. class ObjectConverter {
  5.  
  6. protected $object;
  7.  
  8. protected $params;
  9.  
  10. protected $notConvert;
  11.  
  12. protected $member = 'get';
  13.  
  14. protected $methods = array();
  15.  
  16. protected $methodsName = array();
  17.  
  18. protected $quantityParams = array();
  19.  
  20. private static $exceptionMessage = array(
  21. 'object' => '%s is not an object',
  22. 'array' => '%s must be an array',
  23. 'not-param' => '%s expected parameter',
  24. 'not-exists' => 'public methods %s not exists',
  25. 'bad-quantity-param' => '%s bad quantity parameter in $params',
  26. 'too-many-param' => 'your method have too many parameter - allowed 5'
  27. );
  28.  
  29. public function convert($object, $params = array(), $not_convert = array()) {
  30.  
  31. if (!is_object($object)) {
  32. $this->exception('object', '$object');
  33. }
  34. if (!is_array($params)) {
  35. $this->exception('array', '$params');
  36. }
  37. if (!is_array($not_convert)) {
  38. $this->exception('array', '$not_convert');
  39. }
  40. $this->setObject($object);
  41. $this->setParams($params);
  42. $this->setNotConvert($not_convert);
  43.  
  44. return $this->prepareDataObject();
  45. }
  46.  
  47. protected function setObject($obj) {
  48. $this->object = $obj;
  49. }
  50.  
  51. protected function setParams($params) {
  52. $this->params = $params;
  53. }
  54.  
  55. protected function setNotConvert($not_convert) {
  56. $this->notConvert = array_flip($not_convert);
  57. }
  58.  
  59. protected function prepareDataObject() {
  60.  
  61. $methods = $this->reflectionClass()->getMethods();
  62.  
  63. for ($i = 0; $i < count($methods); $i++) {
  64.  
  65. if ($methods[$i]->isPublic()
  66. && $this->isMember($methods[$i]->name)
  67. && $this->isConvertMethod($methods[$i]->name))
  68. {
  69. $this->methods[] = $methods[$i];
  70. $this->methodsName[] = $methods[$i]->name;
  71. $this->quantityParams[] = $methods[$i]->getNumberOfRequiredParameters();
  72. }
  73. }
  74.  
  75. return count($this->methodsName) > 0 ? $this : $this->exception('not-exists', $this->member);
  76. }
  77.  
  78. public function toArray() {
  79.  
  80. for ($i = 0; $i < count($this->methodsName); $i++) {
  81.  
  82. if (0 < $this->quantityParams[$i]) {
  83.  
  84. $result[$this->createIndex($i)] = $this->withParams($i);
  85. } else {
  86. $result[$this->createIndex($i)] = $this->withoutParams($i);
  87. }
  88. }
  89.  
  90. return $result;
  91. }
  92.  
  93. protected function withParams($i) {
  94.  
  95. $method_name = $this->methodsName[$i];
  96.  
  97.  
  98. if (!isset($this->params[$method_name])) {
  99. $this->exception('not-param', $method_name);
  100. }
  101.  
  102. $params = $this->params[$method_name];
  103.  
  104. if ($this->quantityParams[$i] == count($this->params[$method_name])) {
  105.  
  106. switch ($this->quantityParams[$i]) {
  107. case 1 : return $this->object->$method_name($params[0]);
  108. break;
  109. case 2 : return $this->object->$method_name($params[0], $params[1]);
  110. break;
  111. case 3 : return $this->object->$method_name($params[0], $params[1], $params[2]);
  112. break;
  113. case 4 : return $this->object->$method_name($params[0], $params[1], $params[2], $params[3]);
  114. break;
  115. case 5 : return $this->object->$method_name($params[0], $params[1], $params[2], $params[3], $params[4]);
  116. break;
  117. default : $this->exception('too-many-param', $method_name);
  118. }
  119. } else {
  120. $this->exception('bad-quantity-param');
  121. }
  122. }
  123.  
  124. protected function reflectionClass() {
  125. return new \ReflectionClass($this->object);
  126. }
  127.  
  128. protected function withoutParams($i) {
  129.  
  130. $method_name = $this->methodsName[$i];
  131.  
  132. return $this->object->$method_name();
  133. }
  134.  
  135. protected function createIndex($i) {
  136.  
  137. return strtolower(preg_replace('![a-z]\K(?=[A-Z])!', '_', substr($this->methodsName[$i], strlen($this->member))));
  138. }
  139.  
  140. protected function isConvertMethod($method) {
  141.  
  142. return !isset($this->notConvert[$method]);
  143. }
  144.  
  145. protected function isMember($method) {
  146.  
  147. return $this->member == substr($method, 0, strlen($this->member));
  148. }
  149.  
  150. public function setMemberNameMethods($member) {
  151.  
  152. $this->member = $member;
  153. return $this;
  154. }
  155.  
  156. protected function exception($index, $var_name = null) {
  157.  
  158. throw new Exception(sprintf(self::$exceptionMessage[$index], $var_name));
  159. }
  160.  
  161. }
  162. ?>


Poniżej zamieszczam dwa przykłady działania nie tłumacze dokładnie całego procesu zachodzącego w klasie, ponieważ zależy mi na waszej ocenie czytelności/przejrzystości kodu. Kod jest kompletny można go odpalić.

  1.  
  2. class Example {
  3.  
  4. protected $enlargement = 'txt';
  5. protected $file = 'log';
  6.  
  7. public function getEnlargement() {
  8. return $this->enlargement[0] !== '.' ? '.' . $this->enlargement : $this->enlargement;
  9. }
  10.  
  11. public function getFileName() {
  12. return $this->file;
  13. }
  14.  
  15. public function getLengthFileName() {
  16. return strlen($this->file);
  17. }
  18.  
  19. }
  20. $c = new ObjectConverter();
  21. $example = new Example();
  22.  
  23. try {
  24.  
  25. $result = $c->convert($example)
  26. ->toArray();
  27.  
  28. } catch (Exception $e) {
  29.  
  30. echo $e->getMessage();
  31. }
  32. echo '<pre>';
  33. print_r($result);
  34. echo '<pre>';
  35. /*
  36. Array
  37. (
  38.   [enlargement] => .txt
  39.   [file_name] => log
  40.   [length_file_name] => 3
  41. )
  42. */
  43. class Example2 {
  44.  
  45. public function calculateAvg($a, $b) {
  46. return @($a / $b);
  47. }
  48.  
  49. public function calculateSum($a, $b) {
  50. return @($a * $b);
  51. }
  52.  
  53. public function calculateDiff($a, $b) {
  54. return $a - $b;
  55. }
  56.  
  57. public function calculatePi($a) {
  58. return 3.14 * $a;
  59. }
  60.  
  61. }
  62. $c = new ObjectConverter();
  63. $example2 = new Example2();
  64. $params = array(
  65. 'calculateAvg' => array(5, 25),
  66. 'calculateSum' => array(5, 55),
  67. 'calculateDiff' => array(20, 5),
  68. );
  69. $notConvert = array('calculatePi');
  70.  
  71. try {
  72.  
  73. $result = $c->setMemberNameMethods('calculate')
  74. ->convert($example2, $params, $notConvert)
  75. ->toArray();
  76.  
  77. } catch (Exception $e) {
  78.  
  79. echo $e->getMessage();
  80. }
  81. echo '<pre>';
  82. print_r($result);
  83. echo '<pre>';
  84. /*
  85. Array
  86. (
  87.   [avg] => 0.2
  88.   [sum] => 275
  89.   [diff] => 15
  90. )
  91. */
  92.  
em1X
Jakie jest Twoje pytanie?
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.