Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- interface ApiOutputStrategy
- {
- public function handle(): string;
- }
- class JsonOutput implements ApiOutputStrategy
- {
- public function __construct($data)
- {
- $this->data = $data;
- }
- public function handle(): string
- {
- return json_encode($this->data);
- }
- }
- class XmlOutput implements ApiOutputStrategy
- {
- public function __construct($data)
- {
- $this->data = $data;
- }
- public function handle(): string
- {
- $xml = '<root>';
- foreach($this->data as $key => $value)
- {
- $xml .= "<$key>$value</$key>";
- }
- $xml .= '</root>';
- return $xml;
- }
- }
- class SerializedArrayOutput implements ApiOutputStrategy
- {
- public function __construct($data)
- {
- $this->data = $data;
- }
- public function handle(): string
- {
- return serialize($this->data);
- }
- }
- class ApiOutput
- {
- /**
- * @param ApiOutputStrategy $strategy
- */
- public function __construct(ApiOutputStrategy $strategy)
- {
- $this->strategy = $strategy;
- }
- /**
- * @return void
- */
- public function output()
- {
- echo $this->strategy->handle();
- }
- }
- $data = [
- 'name' => 'test',
- 'secondName' => 'test2',
- 'age' => 25
- ];
- $strategy = new JsonOutput($data);
- $api = new ApiOutput($strategy);
- $api->output();
- echo "\n\n";
- $strategy = new XmlOutput($data);
- $api = new ApiOutput($strategy);
- $api->output();
- echo "\n\n";
- $strategy = new SerializedArrayOutput($data);
- $api = new ApiOutput($strategy);
- $api->output();
- /*
- result:
- {"name":"test","secondName":"test2","age":25}
- <root><name>test</name><secondName>test2</secondName><age>25</age></root>
- a:3:{s:4:"name";s:4:"test";s:10:"secondName";s:5:"test2";s:3:"age";i:25;}
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement