Example of Layered Architecture

The Model

Continuing with the previous example, we mentioned that different concerns should be split up. In order to do so, all layers should be identified in our original tangled code. Throughout this process, we need to pay special attention to the code conforming to the Model layer, which will be the beating heart of the application:

class Post
{
private $title;
private $content;

public static function writeNewFrom($title, $content)
{
return new static($title, $content);
}

private function __construct($title, $content)
{
$this->setTitle($title);
$this->setContent($content);
}

private function setTitle($title)
{
if (empty($title)) {
throw new RuntimeException('Title cannot be empty');
}

$this->title = $title;
}

private function setContent($content)
{
if (empty($content)) {
throw new RuntimeException('Content cannot be empty');
}

$this->content = $content;
}
}

class PostRepository
{
private $db;

public function __construct()
{
$this->db = new PDO(
'mysql:host=localhost;dbname=my_database',
'a_username',
'4_p4ssw0rd',
[
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4',
]
);
}

public function add(Post $post)
{
$this->db->beginTransaction();

try {
$stm = $this->db->prepare(
'INSERT INTO posts (title, content) VALUES (?, ?)'
);

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

$this->db->commit();
} catch (Exception $e) {
$this->db->rollback();
throw new UnableToCreatePostException($e);
}
}
}

The Model layer is now defined by a Post class and a PostRepository class. The Post class represents a blog post, and the PostRepository class represents the whole collection of blog posts available. Additionally, another layer — one that coordinates and orchestrates the Domain Model behavior — is needed inside the Model. Enter the Application layer:

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

(new PostRepository())->add($post);

return $post;
}
}

The PostService class is what is known as an Application Service, and its purpose is to orchestrate and organize the Domain behavior. In other words, the Application services are the ones that make things happen, and they're the direct clients of a Domain Model. No other type of object should be able to directly talk to the internal layers of the Model layer.

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

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