rrigby / picomapper
Minimalist data mapper built on PicoDb
Requires
- php: >=8.3
- rrigby/picodb: ^10.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.2
- phpunit/phpunit: ^12.5
- rector/rector: ^2.6
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-master
- 6.0.0
- 5.0.0
- 4.1.2
- 4.1.1
- 4.1.0
- dev-improve-update-change-detection
- dev-override-exists
- dev-override-find-columns-and-sum
- dev-fix-null-array-access
- dev-with-one-by-join
- dev-improvement-throw-exceptions
- dev-improvement-throw-exceptions-instead-of-returning-false
- dev-origin-master
- dev-improvement-query-nested-definitions
- dev-improvement-throws-exceptions
- dev-improvement-surface-sql-exceptions
This package is auto-updated.
Last update: 2026-10-21 23:28:38 UTC
README
PicoMapper is a minimalist data mapper built on PicoDb.
Features
- Built on PicoDb
- No configuration files
- License: MIT
Requirements
- PHP >= 8.3
- PDO extension
- Sqlite, Mssql, Mysql or Postgresql
Documentation
Installation
composer require rrigby/picomapper
Setup
use PicoDb\Database; use PicoMapper\Mapper; use PicoMapper\Definition; $db = new Database([...]); $mapper = new Mapper($db);
Concepts
Definition
In order to map to or from the database, a mapping must be built from a definition. A definition consists of a table, a primary key (one or more columns that uniquely identifies a record), columns, children (other definitions) and special options that control things like what is considered a deleted record.
Consider a blog system with posts, comments and authors. A post has one author and many comments, a comment has one author. Assuming posts, comments and authors have their own tables, a suitable definition would look like the following:
$author = (new Definition('authors')) ->withColumns('name') ->readOnly(); $comment = (new Definition('comments')) ->withColumns('content') ->withOne($author, 'author', 'id', 'author_id') ->withDeletionTimestamp('deleted'); $post = (new Definition('posts')) ->withColumns('title', 'content') ->withOne($author, 'author', 'id', 'author_id') ->withMany($comment, 'comments', 'post_id') ->withDeletionTimestamp('deleted'); $mapping = $mapper->mapping($post);
Authors are shared between posts and comments, so the author definition is read-only: it's fetched with the post but never written.
The second constructor argument for Definition is an array of columns that uniquely identify a record within the table.
By default it's ['id'].
Relationships
withOne() and withMany() take the child definition, the property name, the column in the child table, and the column
in the parent table (id by default):
// comments.post_id = posts.id $post->withMany($comment, 'comments', 'post_id'); // authors.id = posts.author_id $post->withOne($author, 'author', 'id', 'author_id');
When the relationship goes through a join table, use withOneByJoin() or withManyByJoin(). After the parent column,
pass the join table, the join table column that references the parent, then the join table column that references
the child:
// posts_tags (post_id, tag_id) links posts to tags $tag = (new Definition('tags'))->withColumns('name'); $post->withManyByJoin($tag, 'tags', 'id', 'id', 'posts_tags', 'post_id', 'tag_id');
Primary keys
Call useAutoIncrement() to let the database generate a single column primary key on insert. Any value in the data is
ignored, and the generated ID is set on the record passed to the children and hooks:
$comment = (new Definition('comments')) ->withColumns('content') ->useAutoIncrement();
Read-only definitions
A definition marked with readOnly() is fetched as normal but never written. Inserts, updates and removals skip it, which
is useful for lookup data such as the authors above.
Soft deletes
With withDeletionTimestamp(), removing a record sets that column to the current UTC time instead of deleting the row,
and fetches ignore records where it is set. Extra columns to set on removal can be added with withDeletionData():
$post = (new Definition('posts')) ->withColumns('title', 'content') ->withDeletionTimestamp('deleted') ->withDeletionData(['deleted_by' => $userId]);
Data to be set on insert and update can be set by calling withCreationData() and withModificationData() respectively. For example if you wanted to add a date_entered and date_modified columns to the $post definition, you would enter it as follows:
$post = (new Definition('posts')) ->withColumns('title', 'content') ->withOne($author, 'author', 'id', 'author_id') ->withMany($comment, 'comments', 'post_id') ->withCreationData(['date_entered' => gmdate('Y-m-d G:i:s')]) ->withModificationData(['date_modified' => gmdate('Y-m-d G:i:s')]) ->withDeletionTimestamp('deleted');
Mapping
Mappings have the same interface as PicoDb's Table class. That is, you can chain conditions and call findOne() or
findAll() to fetch records or insert(), update(), remove() and save() to modify records. In all cases, the
definition will be used to intelligently return or accept a structured array.
In the example above you could fetch or save a post using the following structured array, and all table relationships will be followed automatically.
$data = [ 'id' => 'abc123', 'author_id' => 'zxy321', 'author' => [ 'id' => 'zxy321', 'name' => 'John Doe' ], 'title' => 'Data Mappers Rock', 'content' => 'They save you time', 'comments' => [ [ 'id' => 'def456', 'post_id' => 'abc123', 'author_id' => 'zxy321', 'author' => [ 'id' => 'zxy321', 'name' => 'John Doe' ], 'content' => 'Did you like my post?' ], [ 'id' => 'hij789', 'post_id' => 'abc123', 'author_id' => 'klm012', 'author' => [ 'id' => 'klm012', 'name' => 'Jane Doe' ], 'content' => 'Nice article!' ], ] ]; $mapper->mapping($post)->save($data); $saved = $mapper->mapping($post)->eq('id', 'abc123')->findOne(); // $saved will be identical in structure to $data
save()updates the record if its primary key exists and inserts it otherwise. The data must include the primary key.update()throws aMappingExceptionif the primary key is missing or the record doesn't exist.- Children are synchronised on update: new children are inserted, changed ones updated, and children missing from the data are removed.
- Writes that touch several tables run in a transaction, unless one is already open.
Create a new mapping for each query, as conditions added to a mapping stay on it.
Hooks
Hooks are callbacks that can be triggered when a mapping performs the successful insert, update or removal of a record. A hook registered against a mapper will be used for all top level mappings it creates.
$mapper->registerHook('updated', function ($table, $key, $updated, $original) { printf('Table %s (ID: %s) was updated...', $table, implode(':', $key)); });
Every hook receives the table name and the record's primary key values. The remaining arguments depend on the event:
| Event | Arguments |
|---|---|
inserted |
$table, $key, $inserted |
updated |
$table, $key, $updated, $original |
removed |
$table, $key |
Transactions and debugging
$mapper->startTransaction(); $mapper->mapping($post)->save($data); $mapper->mapping($comment)->save($commentData); $mapper->closeTransaction(); // Queries logged by PicoDb print_r($mapper->getLogMessages());
$mapper->table('posts') returns a plain PicoDb Table for queries that don't need mapping.
Development
composer test composer phpstan composer rector # dry run, use rector:fix to apply composer cs # dry run, use cs:fix to apply