Skip to content

Instantly share code, notes, and snippets.

@MilesChou
Last active December 2, 2016 05:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MilesChou/c7980023d2a1e2d381b8acfdb7d31e72 to your computer and use it in GitHub Desktop.
Save MilesChou/c7980023d2a1e2d381b8acfdb7d31e72 to your computer and use it in GitHub Desktop.
greeting
<?php
class Client
{
public $greetingRules = [];
public function __construct()
{
$this->greetingRules[] = new MorningGreeting();
$this->greetingRules[] = new AfternoonGreeting();
$this->greetingRules[] = new EveningGreeting();
}
/**
* @param int $hour
*/
public function getGreeting($hour)
{
/**
* @var $greetingRule GreetingRule
*/
foreach ($this->greetingRules as $greetingRule) {
if ($greetingRule->isRight($hour)) {
return $greetingRule->getGreeting();
}
}
throw new Exception("Error when greeting!");
}
}
class MorningGreeting implements GreetingRule
{
public function getGreeting()
{
return "Good Morning";
}
public function isRight($hour)
{
if ($hour >= 6 && $hour < 12) {
return true;
}
return false;
}
}
class AfternoonGreeting implements GreetingRule
{
public function getGreeting()
{
return "Good Afternoon";
}
public function isRight($hour)
{
if ($hour >= 12 && $hour < 18) {
return true;
}
return false;
}
}
class EveningGreeting implements GreetingRule
{
public function getGreeting()
{
return "Good Evening";
}
public function isRight($hour)
{
if ($hour >= 18 && $hour < 22) {
return true;
}
return false;
}
}
interface GreetingRule
{
/**
* @param int $hour
* @return bool
*/
public function isRight($hour);
/**
* @return string
*/
public function getGreeting();
}
$client = new Client();
echo $client->getGreeting(7) . PHP_EOL;
echo $client->getGreeting(13) . PHP_EOL;
echo $client->getGreeting(19) . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment