Papper
Papper copied to clipboard
Possible to map from StdClass to Object
Hey, love what you're doing with this class! Was wondering if there is a way to map from StdClass to Object. I see that we can go from Object to StdClass already.
Thanks
Hi! Thanks for feedback! Unfortunately you can't map StdClass to Object directly, but you can it do through manual mapping configuration. Let me show the example:
<?php
use Papper\MemberOption\MapFrom;
use Papper\Papper;
require_once __DIR__ . '/../vendor/autoload.php';
class User
{
public $name;
public $family;
public $birthday;
}
Papper::createMap('stdClass', 'User')
->forMember('name', new MapFrom('name'))
->forMember('family', new MapFrom('family'))
->forMember('birthday', new MapFrom(function(\stdClass $source) {
return $source->birthday = new \DateTime($source->birthday);
}))
;
$userDTO = new \stdClass();
$userDTO->name = 'John';
$userDTO->family = 'Smith';
$userDTO->birthday = '16 oct 1999';
$user = Papper::map($userDTO)->toType('User');
print_r($user);
/*
* The above example will output:
*
* User Object
* (
* [name] => John
* [family] => Smith
* [birthday] => DateTime Object
* (
* [date] => 1999-10-16 00:00:00
* [timezone_type] => 3
* [timezone] => Asia/Novosibirsk
* )
* )
*
*/
I have an idea to implement dynamic mapping "on the fly" without any validation - it is exactly for the case you are talking. What you think about this? Could you please share your experience with Papper?
The dynamic, convention-based mapping is exactly what I am looking for. I needed to convert a StdClass object to a business object. The example you showed previously is what I've resorted to using. But it would be nice to have this handled by "convention" with the ability to create custom mappings for any fields that fall outside of convention.
On Thu, Oct 16, 2014 at 8:35 AM, Vladimir Komissarov < [email protected]> wrote:
I have an idea to implement dynamic mapping "on the fly" without any validation - it is exactly for the case you are talking. What you think about this? Could you please share your experience with Papper?
— Reply to this email directly or view it on GitHub https://github.com/idr0id/Papper/issues/8#issuecomment-59354147.
Hi,
This is exactly what I'm missing too. It's great mapping between two known types or from a known type to a dynamic object - but a very common case is to map the other way around (from a dynamic object to a known type). Right now, that mapping code shown above is actually more tedious than just mapping the properties yourself. I sort of expect an automapper to be able to map between two objects regardless of type :)
Papper::map($unknownType)->to($unknownType)
Papper::map($knownType)->to($otherKnownType)
Papper::map($knownType)->to($unknownType)
Papper::map($unknownType)->to($knownType)
I want to keep using Papper, I think it's clean and works great but I really need the "dynamic mapping" feature.
Well.. any news? In case of some ideas or direction to go I could prepare an PR.