Skip to content

Instantly share code, notes, and snippets.

@girorme
Last active June 9, 2021 21:25
Show Gist options
  • Save girorme/f1f05d79b87b1a9e30270b9cbe3c7900 to your computer and use it in GitHub Desktop.
Save girorme/f1f05d79b87b1a9e30270b9cbe3c7900 to your computer and use it in GitHub Desktop.
<?php
interface Entity {
}
class Book implements Entity {
}
// REPO
interface Repository {
public function getAll() : array;
public function getOne() : Entity;
public function update(Entity $entity) : void;
public function save() : bool;
}
interface UseCase {}
/*class MysqlRepository implements Repository {
public function getAll() : array;
public function getOne() : Entity;
public function update(Entity $entity) : void;
public function save() : bool;
}*/
/*class InMemoryRepository {
public function getAll() : array;
public function getOne() : Entity;
public function update(Entity $entity) : void;
public function save() : bool;
}*/
class MongoRepository implements Repository {
public function getAll() : array {
return [
'data' => [["id" => 1, "name" => "lorem"], ["id" => 2, "name" => "ipsum"]]
];
}
public function getOne() : Entity {
return new Book();
}
public function update(Entity $entity) : void {
}
public function save() : bool {
return true;
}
}
interface Service {
public function notify() : bool;
}
// SERVICE
class EmailService implements Service {
public function notify() : bool {
// send email, do logic business related to email
return true;
}
}
class BookUseCase implements UseCase {
public function __construct(Repository $repo, Service $service) {
$this->repo = $repo;
$this->service = $service;
}
// POST /book
public function createBookAndNotify() {
$book = $_POST["foo"];
$this->repo->getOne($book);
// do something
// Notify store, etc
$this->service->notify();
}
public function getAllBooks() {
return $this->repo->getAll();
}
}
// index.php CONTROLLER / http request begin here:
$ctl = (new class(){
public function setUseCase(UseCase $usecase) {
$this->useCase = $usecase;
}
public function postBooks() {
$this->useCase->createBookAndNotify();
header('Content-type: application/json');
echo json_encode($this->useCase->getAllBooks());
}
public function getBooks() {
header('Content-type: application/json');
echo json_encode($this->useCase->getAllBooks());
}
});
$useCase = new BookUseCase(new MongoRepository(), new EmailService());
$ctl->setUseCase($useCase);
//echo '<pre>';
//var_dump($_SERVER); exit;
$requestUri = $_SERVER['REQUEST_URI'];
switch($requestUri) {
case '/books':
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
$ctl->getBooks();
break;
case 'POST':
$ctl->postBooks();
break;
}
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment