I have a really simple question. I have an object I loop over using a for each loop. foreach ($houses as $house) there I add an $this->getHouseImage($house->ID) in the loop itself.
When I dump the $houses object it is in it (I only have one house in it, so I’m not sure this is the right way).
So is this the right way to add data to an object?
public function render($settings)
{
foreach ($this->getHouses() as $woning) {
$wordpressPost = $woning->getWordpressPost();
$wordpressPost->price = $woning->prijs->value();
$houses[] = $wordpressPost;
}
foreach ($houses as $house) {
$house->image = $this->getHouseImage($house->ID);
}
return $this->view('component', ['settings' => $settings, 'houses' => $houses]);
}
public function getHouseImage($id)
{
return get_the_post_thumbnail_url($id);
}
Seems to me you can do this with one loop instead of two:
$houses = []; // array needs to be initialised in case $this->getHouses() returns an empty array
foreach ($this->getHouses() as $house) { // either all dutch, or all english, don't mix-and-match
$wordpressPost = $house->getWordpressPost();
$wordpressPost->price = $house->prijs->value();
$wordpressPost->image = $this->getHouseImage($house->ID);
$houses[] = $wordpressPost;
}
Next, I would get rid of the needless indirection to $this->getHouseImage() which is just a direct proxy to another function:
$houses = []; // array needs to be initialised in case $this->getHouses() returns an empty array
foreach ($this->getHouses() as $house) { // either all dutch, or all english, don't mix-and-match
$wordpressPost = $house->getWordpressPost();
$wordpressPost->price = $house->prijs->value();
$wordpressPost->image = get_the_post_thumbnail_url($house->ID);
$houses[] = $wordpressPost;
}
Ideally you’d put this logic in some sort of service instead of in the controller, although it’s not that much code, so it’s not that bad.
So yes, you can add properties to objects like this, although I would recommend defining them, instead of dynamically adding them; it’s not recommend people use that.