Created
February 25, 2020 19:35
-
-
Save mangelsnc/9b7855a814fd0befa2a3aad2d1b0acf9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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!'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
namespace App\Strategy; | |
interface FormatStrategy | |
{ | |
public function execute(string $message): string; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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>'; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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