Skip to content

Commit

Permalink
publisher / dispatcher pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
reinerttomas committed Mar 7, 2024
1 parent be31c45 commit 33ac8ab
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Event/FightStartingEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace App\Event;

use App\Character\Character;

readonly class FightStartingEvent
{
public function __construct(
public Character $player,
public Character $ai,
) {
}
}
26 changes: 26 additions & 0 deletions src/Event/OutputFightStartingSubscriber.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace App\Event;

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class OutputFightStartingSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
FightStartingEvent::class => 'onFightStart',
];
}

public function onFightStart(FightStartingEvent $event): void
{
$io = new SymfonyStyle(new ArrayInput([]), new ConsoleOutput());
$io->note('Fight is starting against: ' . $event->ai->getNickname());
}
}
5 changes: 5 additions & 0 deletions src/Game.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
use App\Builder\CharacterBuilderFactory;
use App\Character\Character;
use App\Character\CharacterType;
use App\Event\FightStartingEvent;
use App\Observer\CanObserverFight;
use Random\RandomException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class Game
{
Expand All @@ -23,11 +25,14 @@ class Game

public function __construct(
private CharacterBuilderFactory $characterBuilderFactory,
private EventDispatcherInterface $eventDispatcher,
) {
}

public function play(Character $player, Character $enemy): Fight
{
$this->eventDispatcher->dispatch(new FightStartingEvent($player, $enemy));

$player->rest();

$fight = new Fight();
Expand Down

0 comments on commit 33ac8ab

Please sign in to comment.