2017 © Pedro Peláez
 

library php-hydrator

Simple object hydrator

image

elisdn/php-hydrator

Simple object hydrator

  • Friday, July 21, 2017
  • by ElisDN
  • Repository
  • 2 Watchers
  • 10 Stars
  • 325 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 2 Versions
  • 11 % Grown

The README.md

PHP Object Hydrator

The library allows to hydrate objects from an array and extract raw objects's values to an array., (*1)

Installation

Install with composer:, (*2)

composer require elisdn/php-hydrator

Usage samples

Hydrating an object from an associative array:, (*3)

$post = $this->hydrator->hydrate(Post::class, [
    'id' => $id,
    'date' => $date,
    'title' => $title,
])

Extracting of object values to an array by list of properies:, (*4)

$data = $this->hydrator->extract($post, ['id', 'date', 'title'])

For example if we have Post entity:, (*5)

class Post
{
    private $id;
    private $title;
    private $date;

    public function __construct($id, $title)
    {
        $this->id = $id;
        $this->title = $title;
        $this->date = new DateTimeImmutable();
    }

    public function getId()
    {
        return $this->id;
    }

    public function getTitle()
    {
        return $this->title;
    }
}

then we can use the hydrator in any repository class:, (*6)

class SqlPostRepository implements PostRepository
{
    private $db;
    private $hydrator;

    public function get($id): Post
    {
        if (!$row = $this->db->selectOne('posts', ['id' => $id])) {
            throw new NotFoundException('Post not found.');
        }

        return $this->hydrator->hydrate(Post::class, [
            'id' => $row['id'],
            'date' => DateTimeImmutable::createFromFormat('Y-m-d', $row['create_date']),
            'title' => $row['title'],
        ]);
    }

    public function persist(Post $post): void
    {
        $data = $this->hydrator->extract($post, ['id', 'date', 'title'])

        $this->db->insert('posts', [
            'id' => $data['id'],
            'create_date' => $data['date']->format('Y-m-d'),
            'title' => $data['title'],
        );
    }
}

The Versions

21/07 2017

dev-master

9999999-dev

Simple object hydrator

  Sources   Download

BSD-3-Clause

The Requires

  • php >=5.4.0

 

The Development Requires

21/07 2017

1.0.0

1.0.0.0

Simple object hydrator

  Sources   Download

BSD-3-Clause

The Requires

  • php >=5.4.0

 

The Development Requires