AcmeDemo
├── src/
│ ├── Book.php
│ ├── BookRepository.php
│ └── BookLookupController.php
├── vendor/
├── app.php
├── composer.json
└── composer.lock
# src/Book.php
<?php
namespace Acme\Todo;
class Book
{
public $title;
public function __construct(string $title)
{
$this->title = $title;
}
}
# src/BookRepository.php
<?php
namespace Acme\Todo;
use React\Mysql\ConnectionInterface;
class BookRepository
{
private $db;
public function __construct(ConnectionInterface $db)
{
$this->db = $db;
}
public function findBook(string $isbn): ?Book
{
$result = $this->db->query(
'SELECT title FROM book WHERE isbn = ?',
[$isbn]
);
if (count($result->resultRows) === 0) {
return null;
}
return new Book($result->resultRows[0]['title']);
}
}
# src/BookLookupController.php
<?php
namespace Acme\Todo;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use React\Http\Message\Response;
class BookLookupController
{
private $repository;
public function __construct(BookRepository $repository)
{
$this->repository = $repository;
}
public function __invoke(ServerRequestInterface $request): ResponseInterface
{
$isbn = $request->getAttribute('isbn');
$book = $this->repository->findBook($isbn);
if ($book === null) {
return new Response(
404,
[],
"Book not found\n"
);
}
$data = $book->title;
return new Response(
200,
[],
$data
);
}
}