Fernando
Fernando

Reputation: 485

How can I build this data structure using an Object instead of an Array?

I'm building a data structure for a Mustache template. I can easily build it using an array. But since I'm trying to learn more about working with Objects, I want to use an Object instead.

$mySlider = array("title" => "Photos of Las Vegas");
$mySlider = array("items" => array());

foreach ( $query as $row ) {
 $newItem = [];
 $newItem["postTitle"] = $row["imageTitle"];
 $newItem["postURL"] = $row["imageURL"];
}

array_push($mySlider["items"], $newItem);

This is my current solution. I don't like it, too much code. By using an Object of "Slider" I'd like to be able to do something like this:

$mySlider = new PhotoSlider("Photos of Las Vegas");

foreach ( $query as $row ) {
 $newPhoto = $mySlider->newPhoto();
 $newPhoto->addProperty("imageTitle", $row["imageTitle"]);
 $newPhoto->addProperty("imageURL", $row["imageURL"]);
}

I know I just made this up but this would be much nicer.

How do I need to write this Object in PHP to make it work this way with only one Class? I got stuck when I noticed I'd need another Object for the "newPhoto()" element, since that would need some methods of its own to do "addProperty", for instance.

I'd appreciate any pointers. Thanks!

Upvotes: 0

Views: 38

Answers (1)

sunshinejr
sunshinejr

Reputation: 4854

You will need to create 2 classes, one for PhotoSlider and one for Photo. Photoslider would have array of Photos, and methods like add the Photo objects to the PhotoSlider, delete etc. Photo class would have the set attribute methods. Like:

$mySlider = new PhotoSlider("Photos of Las Vegas");

foreach ( $query as $row ) {
 $newPhoto = new Photo();
 $newPhoto->addProperty("imageTitle", $row["imageTitle"]);
 $newPhoto->addProperty("imageURL", $row["imageURL"]);
 $mySlider->addPhoto($newPhoto);
}

Upvotes: 1

Related Questions