2

Let's say I have an instance of a class that contains dozens of properties. This class cannot be modified or extended.

I now need to pass some data from this instance to a function. The function just needs a few of these properties and it cannot directly use an instance of a class (it expects an associative array) and also needs some data not present in the instance. So I need to convert the instance to an associative array.

For example I need to convert this:

class Person {

    public $id = 123;
    public $firstName = "John";
    public $lastName = "Something";
    public $address;
    public $city;
    public $zipCode;
    // etc.

}

to this:

array(
    'id' => 123,
    'name' => 'John Something'
);

My question is: is there any known OOP pattern to handle this kind of conversion? I know I could write a simple function to convert from one format to another but I'd like to know what is the "proper" way to do it, basically use a known pattern if possible.

4

2 回答 2

2

As you are asking for a design pattern, the Adapter Pattern might be the most appropriate one

In your example, Person would be the Adaptee and your Adaptor would extend the Array-Class and override the access method. The implementation of the adaptor may vary as you still have to decide whether you want explicity access the adaptees fields or you want to encapsulate a generic access (e.g. with reflection).

Note that this solution is not a realy "conversion" to a standalone array as the data is still backed in your instance of Person which has implications for your requirements you may have:

  • As you also want to add other data fields, you may want to extend the adaptor further according to your logic.
  • Check with your requirements if other array operations should be reflected to the Person instance
于 2013-01-09T09:06:09.470 回答
0

You could, quickly and dirty, try force casting to array:

class Person {

    public $id = 123;
    public $firstName = "John";
    public $lastName = "Something";
    public $address;
    public $city;
    public $zipCode;
    // etc.

}

$person = new Person;
var_dump( (array)$person);

Output:

array(6) {
  ["id"]=>
  int(123)
  ["firstName"]=>
  string(4) "John"
  ["lastName"]=>
  string(9) "Something"
  ["address"]=>
  NULL
  ["city"]=>
  NULL
  ["zipCode"]=>
  NULL
}

Working example: http://ideone.com/EddQI8

于 2013-01-08T06:31:25.510 回答