Skip to content

Object translator#429

Closed
milo wants to merge 10 commits intodg:masterfrom
milo:pull-serialize-object2
Closed

Object translator#429
milo wants to merge 10 commits intodg:masterfrom
milo:pull-serialize-object2

Conversation

@milo
Copy link
Copy Markdown
Collaborator

@milo milo commented Nov 22, 2022

This commit brings Dibi\ObjectTranslator which allows to translate any object into Dibi\Expression. For example:

class Translator implements Dibi\ObjectTranslator
{
    public function translateObject(object $o): ?Dibi\Expression
    {
        return match (true) {
            $o instanceof Person => new Dibi\Expression('?', $o->id),
            $o instanceof IpAddress => new Dibi\Expression('?::inet', $o->address),
            default => null,
    }
}

$db->setObjectTranslator(new Translator);
$db->insert('table', [
    'person_id' => new Person,
    'from_ip' => IpAddress::fromGlobal(),
]);

Some notes:

  • object translator is never used when value modifier is used
  • the Dibi\Literal and Dibi\Expression is never passed into object translator
  • object translators can be chained via Connection::getObjectTranslator() getter
  • even it's not so important, I've run tests locally on SQLite, MariaDB, PostgreSQL, SQLServer (and its PDO variants)

Before this PR I've tried another a little bit different approach - set object translator per class:

$db->setObjectTranslator(string $class, ObjectTranslator $translator);

It is probably more deterministic but it is harder to setup a lazy Dibi\Translator and it brings problem with searching object translator for child classes.

@milo milo force-pushed the pull-serialize-object2 branch 8 times, most recently from cfb0688 to a9e5cbd Compare November 22, 2022 09:40
@milo milo force-pushed the pull-serialize-object2 branch from a9e5cbd to 2292a71 Compare November 22, 2022 09:46
Object translator allows to translate any object passed to Translator into Dibi\Expression.
@milo
Copy link
Copy Markdown
Collaborator Author

milo commented Feb 4, 2023

Solved by 2nd version #432

@milo milo closed this Feb 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants