I am getting to a point in my application where there seems to be a lot of presentation logic in my models:
<?php foreach ($this->users as $user): ?>
<span class="phone">
<?php echo $user->getPhoneNumberFormattedAsText(); ?>
</span>
<?php endforeach; ?>
At first, I started approaching this as a need for View Helpers:
<span class="phone"><?php echo $this->userPhone($user->getPhone()); ?></span>
However, I've started running into a problem where I have lots of little View Helpers that are specific to certain models, that don't need to take up an entire file. It would be nice if I could group this presentation logic together and keep it out of the model. I think this is when the decorator pattern makes sense.
"The decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically."
I have seen a few examples online, but no real, practical examples of code. I would like to know if you have successfully used this pattern in your PHP application and what a PHP example of this should look like.
I've implemented a decorator pattern for my php application. Basically it's a wrapper class to a xml configuration file where I define my basic needs. To simplify I use a pizza as an example. Then I have a class for each ingredient and wrap it around the other class. In the end I call the prize method of each class and it gives me the sum of everything.
$order = new pizza($xml_file);
$order = new add_salami($order);
$order = new add_cheese($order);
$order = new add_tomato($order);
$order = $order->prize();
You need to maintain a pointer to the current object in every ingredient class. When you call the php new function you can use it to backup the current object. It's a bit like a linked list (of objects). Then you can call the prize() method of the last object and loop through all other classes. But to decorate you need to add new classes. You can also replace the $xml_file with a start value. I've all my decorator class in one file. A decorator class can looks like this:
class add_salami {
protected $order;
protected $prize;
public function __construct ($order) {
$this->order = $order;
$this->prize = $order->getPrize();
}
public function getPrize() {
return $this->prize + 10;
}
}
I keep many of these tiny decorator classes in a huge file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With