Skip to content

Instantly share code, notes, and snippets.

@SelrahcD
Last active April 13, 2018 09:15
Show Gist options
  • Save SelrahcD/417cc0520cce502fca485a88c7b455a4 to your computer and use it in GitHub Desktop.
Save SelrahcD/417cc0520cce502fca485a88c7b455a4 to your computer and use it in GitHub Desktop.
Exceptional Events
<?php
class User {
private $beers = 0;
public $id;
/**
* User constructor.
*/
public function __construct($id) {
$this->id = $id;
}
public function drinkBeer()
{
$this->beers++;
if($this->beers == 1) {
throw ExceptionalEventSystemCoded::by($this->id);
}
elseif($this->beers > 1) {
throw TooMuchBeerWasDrunk::by($this->id);
}
}
}
class UserRepo {
private $users = [];
public function getById($id)
{
return $this->users[$id];
}
public function add(User $user) {
$this->users[$user->id] = $user;
}
}
class BeerDrunk extends Exception {
public $user;
public static function by($user)
{
$event = new self(sprintf('A beer was drunk by user %s', $user));
$event->user = $user;
return $event;
}
}
class ExceptionalEventSystemCoded extends Exception {
public $user;
public static function by($user)
{
$event = new self(sprintf('An exceptional event system was coded by user %s', $user));
$event->user = $user;
return $event;
}
}
class TooMuchBeerWasDrunk extends Exception {
public $user;
public static function by($user)
{
$event = new self(sprintf('Too much beer was drunk by user %s', $user));
$event->user = $user;
return $event;
}
}
class SomeoneFeltAsleep extends Exception {
public $user;
public static function thatSomeoneIs($user)
{
$event = new self(sprintf('User %s felt asleep', $user));
$event->user = $user;
return $event;
}
}
$userRepo = new UserRepo();
$user1 = new User(1);
$userRepo->add($user1);
$handlers = [
BeerDrunk::class => function(BeerDrunk $beerDrunk) use($userRepo) {
$user = $userRepo->getById($beerDrunk->user);
$user->drinkBeer();
},
ExceptionalEventSystemCoded::class => function(ExceptionalEventSystemCoded $systemCoded) use($userRepo) {
$user = $userRepo->getById($systemCoded->user);
$user->drinkBeer();
},
TooMuchBeerWasDrunk::class => function(TooMuchBeerWasDrunk $tooMuchBeerWasDrunk) {
throw SomeoneFeltAsleep::thatSomeoneIs($tooMuchBeerWasDrunk->user);
}
];
$param = null;
$handler = function($param) {
throw BeerDrunk::by(1);
};
do {
$eventCatched = false;
try {
$handler($param);
}
catch(Exception $e) {
$eventCatched = true;
echo $e->getMessage() . PHP_EOL;
$handler = isset($handlers[get_class($e)]) ? $handlers[get_class($e)] : null;
$param = $e;
}
} while($handler && $eventCatched);
// A beer was drunk by user 1
// An exceptional event system was coded by user 1
// A beer was drunk by user 1
// Too much beer was drunk by user 1
// User 1 felt asleep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment