In modern PHP Applications there is often a need for coping with data mappings. Many applications use class
methods like fromArray or fromXXX on their Models / Entities. This might work for built-in types like array
or objects in the same context. But as soon as someone tries to map from an object out of context, things get messy.
This library provides a clean and decoupled way to cope with Data Mappings.
The preferred method of installation is via Composer. The following command will add the appropriate requirement to your composer.json:
composer require dertechie/datamapping
Let's assume we have a simple Object that we want to map:
<?phpnamespaceDerTechie\Entities;
class MyObject
{
use MappableTrait;
privatestring$id;
privatestring$name;
/** * @return string */publicfunctiongetId(): string
{
return$this->id;
}
/** * @param string $id */publicfunctionsetId(string$id): void
{
$this->id = $id;
}
/** * @return string */publicfunctiongetName(): string
{
return$this->name;
}
/** * @param string $name */publicfunctionsetName(string$name): void
{
$this->name = $name;
}
}To enable mapping for this object we simply need to add the MappableTrait to the class. This will add the from method
to the object.
In order to map the object, we need a Mapper class that handles all of our mappings.
<?phpnamespaceDerTechie\Mappers;
useDerTechie\DataMapping\AbstractMapper;
useDerTechie\Entities\MyObject;
class MyObjectMapper extends AbstractMapper
{
publicstaticfunctiongetType(): string
{
return MyObject::class;
}
publicfunctionfromArray(array$source): MyObject
{
$obj = newMyObject();
$obj->setId($source['id']);
$obj->setName($source['name']);
return$obj;
}
publicfunctionfromCreateMyObjectRequest(CreateMyObjectRequest$request): MyObject
{
$obj = newMyObject();
$obj->setId($request->input('id'));
$obj->setName($request->input('name'));
return$obj;
}
publicfunctiongetMappings(): array
{
return [
newMapping('array', [$this, 'fromArray']),
newMapping(CreateMyObjectRequest::class, [$this, 'fromCreateMyObjectRequest'])
];
}
}The key parts here are the class method getType() and the method getMappings(). getType() defines the type this
Mapper is responsible for mapping to. The getMappings() method expects to return an array of available Mappings. The
first parameters defines the type this mapping maps to, and the second parameter defines the callback that is used for
the mapping.
To use the mapper, it needs to be registered. To do so simply call:
MapperRegistry::register(MyObjectMapper::class)
Now you can use the convenient from method on your object to map it: MyObject::from(['id' => '1', 'name' => 'Foo']);