Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created August 13, 2019 09:32
Show Gist options
  • Save kobus1998/1b392588527e0875559b66d83810a8ec to your computer and use it in GitHub Desktop.
Save kobus1998/1b392588527e0875559b66d83810a8ec to your computer and use it in GitHub Desktop.
Strategy pattern
<?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;}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment