Reputation: 90794
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.
Upvotes: 3
Views: 3401
Reputation: 792
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:
Upvotes: 2
Reputation: 25435
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
Upvotes: 0