chukShirley
8/12/2015 - 9:41 PM

Persistence

Persistence

<?php
class PostMapper
{
    public function objectToDb(Post $post)
    {
        return [
            'title' => $post->getTitle(),
            'content' => $post->getContent()
        ];
    }
}
<?php
class PostRepository
{
    private $postMapper;
    private $postTableGateway;
    
    public function __construct(PostMapper $postMapper, PostTableGateway $postTableGateway)
    {
        $this->postMapper = $postMapper;
        $this->postTableGateway = $postTableGateway;
    }
    
    public function save(Post $post)
    {
        // Convert from domain object to array
        $post = $this->postMapper->objectToDb($post);
        
        // Save to database
        $this->postTableGateway->create($post);
        
        return true;
    }
}
<?php
class PostService
{
    private $postRepository;
    
    public function __construct(PostRepository $postRepository)
    {
        $this->postRepository = $postRepository;
    }
    
    public function publish(Post $post)
    {
        $this->postRepository->save($post);
    }
}