Skip to content

Instantly share code, notes, and snippets.

@mangelsnc
Created February 25, 2020 19:35
Show Gist options
  • Save mangelsnc/9b7855a814fd0befa2a3aad2d1b0acf9 to your computer and use it in GitHub Desktop.
Save mangelsnc/9b7855a814fd0befa2a3aad2d1b0acf9 to your computer and use it in GitHub Desktop.
<?php declare(strict_types=1);
namespace App;
use App\Strategy\FormatContext;
use App\Strategy\HtmlFormatStrategy;
use App\Strategy\MarkdownFormatStrategy;
$context = new FormatContext();
$context->setStrategy(new HtmlFormatStrategy());
echo $context->format('Hi!');
$context->setStrategy(new MarkdownFormatStrategy());
echo $context->format('Hi!');
<?php declare(strict_types=1);
namespace App\Strategy;
class FormatContext
{
private $strategy;
private $message;
public function setStrategy(Strategy $strategy): void
{
$this->strategy = $strategy;
}
public function format(string $message): string
{
if (null === $this->strategy) {
throw new RuntimeException('Missing strategy');
}
return $this->strategy->execute($message);
}
}
<?php declare(strict_types=1);
namespace App\Strategy;
interface FormatStrategy
{
public function execute(string $message): string;
}
<?php declare(strict_types=1);
namespace App\Strategy;
class HtmlFormatStrategy implements FormatStrategy
{
public function execute(string $message): string
{
return '<html><body><h1>' . $message . '</h1></body></html>';
}
}
<?php declare(strict_types=1);
namespace App\Strategy;
class MarkdownFormatStrategy implements FormatStrategy
{
public function execute(string $message): string
{
return '# ' . $message;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment