Skip to content

Instantly share code, notes, and snippets.

@ancarebeca
Last active March 11, 2019 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ancarebeca/b4696d95cf446b82f70253da3d4f54ec to your computer and use it in GitHub Desktop.
Save ancarebeca/b4696d95cf446b82f70253da3d4f54ec to your computer and use it in GitHub Desktop.
<?php
class Context
{
private $strategy;
public function __construct(StrategyInterface $strategy)
{
$this->strategy = $strategy;
}
public function applyStrategy(Book $book)
{
return $this->strategy->formatTitle($book);
}
}
interface StrategyInterface
{
public function formatTitle(Book $book);
}
class StrategyUppercase implements StrategyInterface
{
public function formatTitle(Book $book)
{
return strtoupper($book->getTitle());
}
}
class StrategyLowercase implements StrategyInterface
{
public function formatTitle(Book $book)
{
return strtolower($book->getTitle());
}
}
class StrategyLcfirst implements StrategyInterface
{
public function formatTitle(Book $book)
{
return lcfirst($book->getTitle());
}
}
class StrategyUcwords implements StrategyInterface
{
public function formatTitle(Book $book)
{
return ucwords($book->getTitle());
}
}
class Book
{
private $title;
function __construct(string $title_in)
{
$this->title = $title_in;
}
function getTitle(): string
{
return $this->title;
}
}
$book = new Book('Harry Potter');
echo "Title: " . $book->getTitle()."<br/>";
$strategyUppercase = new StrategyUppercase();
$context = new Context($strategyUppercase);
echo "Strategy uppercase: " . $context->applyStrategy($book)."<br/>";
$strategyLowercase = new StrategyLowercase();
$context = new Context($strategyLowercase);
echo "Strategy lowercase: " . $context->applyStrategy($book)."<br/>";
$strategyLcfirst = new StrategyLcfirst();
$context = new Context($strategyLcfirst);
echo "Strategy first character in lowercase: " . $context->applyStrategy($book)."<br/>";
/**** Output: ***************************************
* Title: Harry Potter
* Strategy uppercase: HARRY POTTER
* Strategy lowercase: harry potter
* Strategy first character in lowercase: harry Potter
*****************************************************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment