I should build an importer in PHP. So below you can see how it should work or how it currently works.
This is only a small example, the real importer is much bigger so the import() method is also very big :(
function import($src, $dest)
{
// Name
if(!$dest->nameFixed()) {
$dest->setName($src->getFirstName() . $src->getLastName());
}
// City
$city = City::searchByName($src->getCity());
if ($city instanceof City) {
$dest->setCityById($city);
} else {
$dest->setCity($src->getCity())
}
// Image
$now = new DateTime();
if ($src->getImage() && $now->diff($src->getBirthdate())->format('%y') >= 18) {
$image = myDowndloader::download($src->getImage());
$dest->setImage($image);
}
// Birthdate
$dest->setBirthdate($src->getBirthdate());
// ...
}
some ideas:
class Translate
{
protected $src = NULL;
protected $dest = NULL;
public function __construct($src, $dest)
{
$this->src = $src;
$this->dest = $dest;
}
public function importName()
{
if(!$this->dest->nameFixed()) {
$this->dest->setName($this->src->getFirstName() . $this->src->getLastName());
}
}
public function importCity() {
$city = City::searchByName($this->src->getCity());
if ($city instanceof City) {
$this->dest->setCity($city);
} else {
$this->dest->setCity(City::createByName($this->src->getCity()));
}
}
// ...
}
or a little bit more fancy:
namespace Translate
{
class Abstract
{
protected $src = NULL;
protected $dest = NULL;
public function __construct($src, $dest) { ... }
abstract pubilc function import();
}
class Name extends Abstract
{
public function import()
{
if(!$this->dest->nameFixed()) {
$this->dest->setName($this->src->getFirstName() . $this->src->getLastName());
}
}
// ...
}
}
I'm not really happy with the examples above.
The main problem is how to call the methods (1st solution) or create the Objects (2nd solution).
One option is to get all methods or classes dynamicly by get_class_methods() and parse the method names for /import\w+/. But I'm not sure how performant this is.
The other option is to call the methods staticly but there is also a danger to forgot a method to call...