One of my favorite tools with my .NET developments is definitely AutoMapper. It allows to easily mapping objects to other objects by generating default maps for graph of objects base on the name of the different members.

I found it quite a shame that such a tool did not exist on the PHP platform. So I started a new Symfony2 bundle to palliate this lack.

How the AutoMapperBundle works

You can find it here: https://github.com/michelsalib/BCCAutoMapperBundle.

As a quick example here to show you how you can map objects together. Here is your model:

[cc_php]
name = $name;
$this->description = $description;
$this->author = new SourceAuthor($author);
}

public getName() {
return $this->name;
}

public getDescription() {
return $this->description;
}

public getAuthor() {
return $this->author;
}
}

class SourceAuthor {
private $name;

public __construct($name) {
$this->name = $name;
}

public getName() {
return $this->name;
}
}

class DestinationPost {
private $title;
private $description;
private $author;

public getTitle() {
return $this->title;
}

public setTitle($title) {
$this->title = title;
}

public getDescription() {
return $this->description;
}

public setDescription($description) {
$this->description = description;
}

public getAuthor() {
return $this->author;
}

public setAuthor($author) {
$this->author = author;
}
}
[/cc_php]

Then, in you application:

[cc_php]
get(‘bcc_auto_mapper.mapper’);
// create default map and route members
$mapper->createMap(‘MySourcePost’, ‘MyDestinationPost’)
->route(‘title’, ‘name’)
->route(‘author’, ‘author.name’);

// create objects
$source = new SourcePost(‘AutoMapper Bundle’, ‘A great bundle’, ‘Michel’);

// map
$destination = $mapper->map($source, $new DestinationPost());

echo $destination->getTitle(); // outputs ‘AutoMapper Bundle’
echo $destination->getDescription(); // outputs ‘A great bundle’
echo $destination->getAuthor(); // outputs ‘Michel’
[/cc_php]

Read the doc on the github to find more explanation and more functionalities: https://github.com/michelsalib/BCCAutoMapperBundle.

This is a very light implementation and some cases are not covered yet (such as dynamic graph creation). Please, don’t hesitate to fork me and provide feedback.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s