nilportugues / sql-repository

[PHP 7] SQL Repository implementation
http://nilportugues.com
MIT License
36 stars 3 forks source link

Mapping allows deep objects. #10

Closed nilportugues closed 8 years ago

nilportugues commented 8 years ago

This means modifying all the methods using map()... or wrap them into a new function instead.

Test example:

    public function map()
    {
        return [
            'userId' => 'user_id',
            'gender' => 'gender',
            'name.firstName' => 'first_name',
            'name.lastName' => 'last_name',
            'name.fullName' => 'name',
        ];
    }

Being the original class:

class User
{
    protected $gender;
    protected $name;
    protected $userId;

    public function __construct(UserId $userId, Name $name, Gender $gender)
}

class Name
{
    public function __construct(string $firstName, string $lastName, string $name)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->name = $name;
    }
nilportugues commented 8 years ago

Use serializer to convert object to dot notation

nilportugues commented 8 years ago

With the usage of nilportugues/serializer problem is EASILY solved.

The method "toArray" for the Mapping lacks of any sense having this, which is not bad as it would simply the mapping.

<?php
 /**
     * @param QueryBuilder $query
     * @param Identity     $value
     * @param bool         $isInsert
     */
    protected function populateQuery(QueryBuilder $query, Identity $value, $isInsert)
    {
        $mappings = $this->mapping->map();
        if (!$isInsert) {
            $mappings = $this->mappingWithoutIdentityColumn();
        }

        $serializer = new DeepCopySerializer(new FlatArrayTransformer()); //this should become a singleton
        $object = $serializer->serialize($value); //this would require an inmemory registry

        $setOperation = ($isInsert) ? 'setValue' : 'set';

        foreach ($mappings as $objectProperty => $sqlColumn) {
            $this->mappingGuard($objectProperty, $object, $value);
            $placeholder = ':'.$sqlColumn;
            $query->$setOperation($sqlColumn, $placeholder);
            $query->setParameter($placeholder, $object[$objectProperty]); //this has been changed too.
        }
    }
nilportugues commented 8 years ago

https://github.com/PHPRepository/php-sql-repository/commit/a30093058ea0553720d5965f68614474ca99d908