kishanio
kishanio

Reputation: 7089

Multiple Array elements to Class Object

What is best practices to convert multiple array objects into class objects?

I have following use case,

class Queue {
    private $id;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    private $name;

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }
    public static function getAll( ) {

        // Guzzle HTTP Request returns JSON 
        $responseArray = json_decode ( $response->getBody() );
    }

}

This is part of composer package. So now when using this Queue we can request multiple Queues from parent application. Now how do i convert this json response to Queue Object.

Also is it a good decision to declare getAll() method static?

Upvotes: 2

Views: 59

Answers (2)

Niki van Stein
Niki van Stein

Reputation: 10734

What @Hassan says is true, if the keys are not the same or overlap than you can use This answer. You basically need to cast the object given by json_decode to the Queu object and return it.

Static in this case makes sense, because you will create and return a Queu object here, if you first need to make the Queu object and than return another one, it makes little sense.

Upvotes: 2

user377628
user377628

Reputation:

I assume the JSON response contains an associative array, with the keys being the property names you want in your object. If so, you can use the solution found in this answer. Basically, you just iterate through the array and use the key found in your array as the property name and the value as the property value:

$queue = new Queue();
foreach ($array as $key => $value)
{
    $queue->$key = $value;
}

Upvotes: 3

Related Questions