2

This is more of a best practice question than anything.

Let's say I have a form:

<form action="self.php" method="POST">
    <input type="text" name="aA" />
    <input type="text" name="aB" />
    <input type="text" name="aC" />
</form>

And a corresponding class in PHP:

class A
{
    public function getA(){
        return $this->a;
    }

    public function setA($a){
        $this->a = $a;
    }

    public function getB(){
        return $this->b;
    }

    public function setB($b){
        $this->b = $b;
    }

    public function getC(){
        return $this->c;
    }

    public function setC($c){
        $this->c = $c;
    }

    private $a;
    private $b;
    private $c;
}

And somehow I manage to send the data from the form. Now, I need the form data transformed into an instance of A.

What I'm currently doing is the following:

abstract class AStrategy {
    public function doMapping(){
        $a = new A();
        if (isset($_POST['aA']) === true) {
            $a->setA($_POST['aA']);
        }
        ... (same for b and c)
        return $a; //A completely mapped object
    }
}

And I'm extremely aware this is pretty much bad practice (violating DRY).

  • What's the best practice to do this?
  • What if I have a complex object tree? What if I need to map related objects at the same time?
  • Who should do the mapping? Who should create the object and such?

Thank you beforehand.

Carlos Vergara
  • 3,592
  • 4
  • 31
  • 56

1 Answers1

5

For simple objects, use a constructor:

public function __construct($a, $b, $c) {
    $this->a = $a;
    $this->b = $b;
    $this->c = $c;
}

For more complex objects, use a Mapper:

class AMapper {
    public function fetch(A $aObject) {}
}
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • I'm about to be convinced a mapper is what I need. But I'm just wondering, how do I tell the system what mapper do I want it to instance? By the way, I'm using a Front Controller, plus some few other model controllers if it helps. – Carlos Vergara Sep 01 '13 at 06:52
  • @user1231958: I usually go with a 1:1 ratio between Domain Objects and Mappers, each domain object has its own mapper. The mapps is created using a `DataMapperFactory` (which coexists side-by-side with the `DomainObjectFactory`). See the following answer for a very good, in-depth explanation: [How should a model be structured in MVC?](http://stackoverflow.com/a/5864000) – Madara's Ghost Sep 01 '13 at 06:56
  • It seems I've got a lot of rewriting to do. Thank you. – Carlos Vergara Sep 01 '13 at 07:10