Applying Hexagonal Architecture

Continuing with the blog example application, the first concept we need is a Port where the outside world can talk to the application. For this case, we'll use an HTTP Port and its corresponding Adapter. The outside will use the Port to send messages to the application. The blog example was using a database to store the whole collection of blog posts, so in order to allow the application to retrieve blog posts from the database, a Port is needed:

interface PostRepository
{
public function byId(PostId $id);
public function add(Post $post);
}

This interface exposes the Port that the application will retrieve information about blog posts through, and it'll be located in the Domain Layer. Now an Adapter for this Port is needed. The Adapter is in charge of defining the way in which the blog posts will be retrieved using a specific technology:

class PDOPostRepository implements PostRepository
{
private $db;

public function __construct(PDO $db)
{
$this->db = $db;
}

public function byId(PostId $id)
{
$stm = $this->db->prepare(
'SELECT * FROM posts WHERE id = ?'
);

$stm->execute([$id->id()]);

return recreateFrom($stm->fetch());
}

public function add(Post $post)
{
$stm = $this->db->prepare(
'INSERT INTO posts (title, content) VALUES (?, ?)'
);

$stm->execute([
$post->title(),
$post->content(),
]);
}
}

Once we have the Port and its Adapter defined, the last step is to refactor the PostService class so that it uses them. This can be easily achieved by using Dependency Injection:

class PostService
{
private $postRepository;

public function __construct(PostRepositor $postRepository)
{
$this->postRepository = $postRepository;
}

public function createPost($title, $content)
{
$post = Post::writeNewFrom($title, $content);

$this->postRepository->add($post);

return $post;
}
}

This is just a simple example of Hexagonal Architecture. It's a flexible architecture that promotes Separation of Concerns, like Layered Architecture. It also promotes symmetry, due to having an inside application that communicates with the outside via ports. From now on, this will be the foundational architecture used to build and explain CQRS and Event Sourcing.

For more examples about this architecture, you can check out the Appendix, Hexagonal Architecture with PHP. For a more detailed example, you should jump to the Chapter 11, Application, which explains advanced topics like transactionality and other cross-cutting concerns.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset