https://github.com/coderofsalvation/datamapper-minimal
Easily transform arrays and objects in PHP with different layouts into one format
https://github.com/coderofsalvation/datamapper-minimal
Last synced: about 1 year ago
JSON representation
Easily transform arrays and objects in PHP with different layouts into one format
- Host: GitHub
- URL: https://github.com/coderofsalvation/datamapper-minimal
- Owner: coderofsalvation
- License: bsd-3-clause
- Created: 2015-08-21T15:47:14.000Z (almost 11 years ago)
- Default Branch: master
- Last Pushed: 2020-05-28T18:47:18.000Z (about 6 years ago)
- Last Synced: 2025-02-12T06:21:43.522Z (over 1 year ago)
- Language: PHP
- Size: 3.91 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
DataMapper-Minimal
==================
Easily transform arrays and objects with different layouts into one format.
Think importing data from several sources in different formats to generate statistics or exports.
## Usage
$ composer require coderofsalvation/datamapper-minimal
And then
use coderofsalvation\DataMapper;
$datamapper = new DataMapper();
?>
Lets say this is our desired object format:
class MyObject {
public $name;
public $id;
}
But source A provide these object formats:
[{ "short_name": "foo", "ID": 12 },{ "short_name": "bar", "ID":13}]
And oh no! source B has this object format:
Boo
This is going to be a mess...or not?
Nope, we can just define transformations and convert them in batch:
$datamapper->addMapping("A", array(
array( "source" => "short_name", "destination" => "name", "transform" => function($s,&$d){ return $s->short_name; } ),
array( "source" => "id", "destination" => "id", "transform" => function($s,&$d){ return $s->id; } )
));
$datamapper->addMapping("B", array(
array( "source" => "Name", "destination" => "name", "transform" => function($s,&$d){ return $s->Name; } ),
array( "source" => "Id", "destination" => "id", "transform" => function($s,&$d){ return $s->getAttribute("id"); } )
));
// lets do it!
$items = [];
foreach( $Aitems as $item ) $items[] = $datamapper->map("A", $item, new MyObject() );
foreach( $Bitems as $item ) $items[] = $datamapper->map("B", $item, new MyObject() );
print_r($items);
// voila there you go :D
## License
BSD