ValueObject.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Luracast\Restler\Data;
  3. /**
  4. * ValueObject base class, you may use this class to create your
  5. * iValueObjects quickly
  6. *
  7. * @category Framework
  8. * @package Restler
  9. * @author R.Arul Kumaran <arul@luracast.com>
  10. * @copyright 2010 Luracast
  11. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  12. * @link http://luracast.com/products/restler/
  13. *
  14. */
  15. class ValueObject implements iValueObject
  16. {
  17. public function __toString()
  18. {
  19. return ' new ' . get_called_class() . '() ';
  20. }
  21. public static function __set_state(array $properties)
  22. {
  23. $class = get_called_class();
  24. $instance = new $class ();
  25. $vars = get_object_vars($instance);
  26. foreach ($properties as $property => $value) {
  27. if (property_exists($instance, $property)) {
  28. // see if the property is accessible
  29. if (array_key_exists($property, $vars)) {
  30. $instance->{$property} = $value;
  31. } else {
  32. $method = 'set' . ucfirst($property);
  33. if (method_exists($instance, $method)) {
  34. call_user_func(array(
  35. $instance,
  36. $method
  37. ), $value);
  38. }
  39. }
  40. }
  41. }
  42. return $instance;
  43. }
  44. public function __toArray()
  45. {
  46. $r = get_object_vars($this);
  47. $methods = get_class_methods($this);
  48. foreach ($methods as $m) {
  49. if (substr($m, 0, 3) == 'get') {
  50. $r [lcfirst(substr($m, 3))] = @$this->{$m} ();
  51. }
  52. }
  53. return $r;
  54. }
  55. }