<?php | |
/** | |
* Example of useless Repository abstraction for Eloquent. | |
* From "Architecture of complex web applications" book. | |
* https://adelf.tech/2019/architecture-of-complex-web-applications | |
*/ | |
interface PollRepository | |
{ | |
//... some other actions | |
public function save(Poll $poll); | |
public function saveOption(PollOption $pollOption); | |
} | |
class EloquentPollRepository implements PollRepository | |
{ | |
//... some other actions | |
public function save(Poll $poll) | |
{ | |
$poll->save(); | |
} | |
public function saveOption(PollOption $pollOption) | |
{ | |
$pollOption->save(); | |
} | |
} | |
class PollService | |
{ | |
/** @var \Illuminate\Database\ConnectionInterface */ | |
private $connection; | |
/** @var PollRepository */ | |
private $repository; | |
/** @var \Illuminate\Contracts\Events\Dispatcher */ | |
private $dispatcher; | |
public function __construct( | |
ConnectionInterface $connection, | |
PollRepository $repository, | |
Dispatcher $dispatcher) | |
{ | |
$this->connection = $connection; | |
$this->repository = $repository; | |
$this->dispatcher = $dispatcher; | |
} | |
public function create(PollCreateDto $dto) | |
{ | |
if(count($dto->options) < 2) { | |
throw new BusinessException( | |
"Please provide at least 2 options"); | |
} | |
$poll = new Poll(); | |
$this->connection->transaction(function() use ($dto, $poll) { | |
$poll->title = $dto->title; | |
$this->repository->save($poll); | |
foreach ($dto->options as $optionText) { | |
$pollOption = new PollOption(); | |
$pollOption->poll_id = $poll->id; | |
$pollOption->text = $optionText; | |
$this->repository->saveOption($pollOption); | |
} | |
}); | |
$this->dispatcher->dispatch(new PollCreated($poll->id)); | |
} | |
} | |
class PollServiceTest extends \PHPUnit\Framework\TestCase | |
{ | |
public function testCreatePoll() | |
{ | |
$eventFake = new EventFake( | |
$this->createMock(Dispatcher::class)); | |
$repositoryMock = $this->createMock(PollRepository::class); | |
$repositoryMock->method('save') | |
->with($this->callback(function(Poll $poll) { | |
return $poll->title == 'test title'; | |
})); | |
$repositoryMock->expects($this->at(2)) | |
->method('saveOption'); | |
$postService = new PollService( | |
new FakeConnection(), $repositoryMock, $eventFake); | |
$postService->create(new PollCreateDto( | |
'test title', | |
['option1', 'option2'])); | |
$eventFake->assertDispatched(PollCreated::class); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Hi Adelf,
Thank you for your article, it's very helpful.
Btw can you please show up some example about Useful Eloquent Repositories?