Advertisement
Guest User

Untitled

a guest
Aug 25th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. <?php
  2.  
  3. interface ApiOutputStrategy
  4. {
  5. public function handle(): string;
  6. }
  7.  
  8. class JsonOutput implements ApiOutputStrategy
  9. {
  10. public function __construct($data)
  11. {
  12. $this->data = $data;
  13. }
  14.  
  15. public function handle(): string
  16. {
  17. return json_encode($this->data);
  18. }
  19. }
  20.  
  21. class XmlOutput implements ApiOutputStrategy
  22. {
  23. public function __construct($data)
  24. {
  25. $this->data = $data;
  26. }
  27.  
  28. public function handle(): string
  29. {
  30. $xml = '<root>';
  31. foreach($this->data as $key => $value)
  32. {
  33. $xml .= "<$key>$value</$key>";
  34. }
  35. $xml .= '</root>';
  36.  
  37. return $xml;
  38. }
  39. }
  40.  
  41. class SerializedArrayOutput implements ApiOutputStrategy
  42. {
  43. public function __construct($data)
  44. {
  45. $this->data = $data;
  46. }
  47.  
  48. public function handle(): string
  49. {
  50. return serialize($this->data);
  51.  
  52. }
  53. }
  54.  
  55. class ApiOutput
  56. {
  57. /**
  58. * @param ApiOutputStrategy $strategy
  59. */
  60. public function __construct(ApiOutputStrategy $strategy)
  61. {
  62. $this->strategy = $strategy;
  63. }
  64.  
  65. /**
  66. * @return void
  67. */
  68. public function output()
  69. {
  70. echo $this->strategy->handle();
  71. }
  72. }
  73.  
  74.  
  75. $data = [
  76. 'name' => 'test',
  77. 'secondName' => 'test2',
  78. 'age' => 25
  79. ];
  80.  
  81.  
  82. $strategy = new JsonOutput($data);
  83. $api = new ApiOutput($strategy);
  84. $api->output();
  85.  
  86. echo "\n\n";
  87.  
  88. $strategy = new XmlOutput($data);
  89. $api = new ApiOutput($strategy);
  90. $api->output();
  91.  
  92. echo "\n\n";
  93.  
  94. $strategy = new SerializedArrayOutput($data);
  95. $api = new ApiOutput($strategy);
  96. $api->output();
  97.  
  98. /*
  99. result:
  100. {"name":"test","secondName":"test2","age":25}
  101.  
  102. <root><name>test</name><secondName>test2</secondName><age>25</age></root>
  103.  
  104. a:3:{s:4:"name";s:4:"test";s:10:"secondName";s:5:"test2";s:3:"age";i:25;}
  105. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement