Skip to content

Instantly share code, notes, and snippets.

@clue
Created June 9, 2021 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clue/c90ecc4dd1f2d4e39a0dbb4508399aad to your computer and use it in GitHub Desktop.
Save clue/c90ecc4dd1f2d4e39a0dbb4508399aad to your computer and use it in GitHub Desktop.
Fibers make async APIs look like sync APIs – because this example is in fact synchronous from a caller's perspective (fetch, wait, transform, return)
AcmeDemo
├── src/
│   ├── Book.php
│   ├── BookRepository.php
│   └── BookLookupController.php
├── vendor/
├── app.php
├── composer.json
└── composer.lock

Fibers

# 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
        );
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment