views:

61

answers:

3

I'm taking array output from a command-line program and parsing it into a PHP object. Consider this example of a very simple way to do this:

$output = explode("\n", shell_exec(myProg));
$obj = new MyObject();

$offset_field1 = 0;
$offset_field2 = 1;

$obj->Field1 = $output[$offset_field1];
$obj->Field2 = $output[$offset_field2];

This is a bit cumbersome, especially when the number of fields increases. Is there a better design pattern or method to accomplish the same feat in a less heavy-handed manner?

+1  A: 

I guess this should work:

$output = explode("\n", shell_exec(myProg));
$obj = new MyObject();

foreach ($output as $key => $value)
{
    $obj->{'Field' . ($key + 1)} = $value;
}
Alix Axel
My trivial example was not clear on this, but the field names are generally more meaningful than Field1/Field2. I'm looking for a more graceful way to handle the field mapping than a bunch of constants for offsets and manual assignment.
timbonicus
@timbonicus: Then maybe you should try to explain what you're trying to archive a little better because I still don't get it.
Alix Axel
+1  A: 

As it seems you cannot guess the field name from the outpout of your programm, you will have to define it somewhere.

$key_map = array('field_name1', 'field_name2', 'etc');

$obj = new MyObject();

foreach(explode("\n", shell_exec(myProg)) as $k => $v)
{
  if(isset($key_map($k))
    $obj->$key_map[$k] = $v;
}
Benoit Vidis
+1  A: 

Why not put the assignment code in the object?

class MyObject
{
    public function __construct(array $data)
    {
        $this->Field1 = $data['keyname1'];
        $this->Field2 = $data['keyname2'];
        ...
    }
}

or use the get magic method.

class MyObject
{
    protected $data;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function __get($key)
    {
        $map = array('Field1' => 1, 'Feild2' => 2, ...);
        if (isset($map[$key])) {
            return $this->data[$map[$key]];
        }
    }
}
Thanks, I wasn't aware of the magic methods __get/__set. This along with an array map of the field names is a nice solution.
timbonicus