Example of Decorator Pattern, using php8 constructor property promotion

February 1, 2021 ≈ 34 seconds

Design patterns are cool but hard to memorize. I think that emoji and new php8 constructor property promotion help simplify the scheme. Take a look.


<?php

interface Product { public function cost(): int; }

class 📱 implements Product
{
    public function cost(): int { return 699; }
}

class 🎧 implements Product
{
    public function __construct(public Product $product) {}
    public function cost(): int { return $this->product->cost() + 549; }
}

class 🔌 implements Product
{
    public function __construct(public Product $product) {}
    public function cost(): int { return $this->product->cost() + 19; }
}

echo 'only $' . (new 🔌(new 🎧(new 📱)))->cost(); // only $1267
echo 'only $' . (new 🎧(new 🔌(new 📱)))->cost(); // only $1267

Subscribe to our newsletter

If you provide url of your website, we send you free design concept of one element (by our choice)

Subscribing to our newsletter, you comply with subscription terms and Privacy Policy