Что бы инкапсулировать бизнес логику.
Например управление свойством action (см. код) недоступно из клиентского кода, так как публичный сеттер отсутвует.
<?php
declare(strict_types=1);
class Product
{
private string $name;
private float $price;
private bool $action = false;
private array $products = [];
public function __construct(string $name, float $price = 0)
{
$this->name = $name;
$this->price = $price;
}
public function getSummary(): string
{
return $this->action ? '<span style="color: blue">Акция, товар с нименьшей ценой в подарок!!!</span><br>'
. $this->name . ' <span style="color: red"><s>' . $this->price . '</s></span>' : $this->name . ' ' . $this->price;
}
public function getName(): string
{
return $this->name;
}
public function getPrice(): float
{
return $this->action ? 0 : $this->price;
}
public function addProduct(Product $product): self
{
$this->products[] = $product;
$this->priceCalculate();
return $this;
}
public function action(): self
{
if (!empty($this->products)) {
$products = $this->products;
array_multisort(array_map(static function ($product) {
$product->action = false;
return $product->getPrice();
}, $products), SORT_DESC, $products);
$products[array_key_last($products)]->action = true;
$this->priceCalculate();
}
return $this;
}
public function getProduct(): Generator
{
foreach ($this->products as $product) {
yield $product;
}
}
private function priceCalculate(): void
{
$this->price = array_sum(array_map(static function ($product) {
return $product->getPrice();
}, $this->products));
}
}
class Show
{
private Product $item;
public function __construct(Product $item)
{
$this->item = $item;
}
public function handler(): void
{
echo '<h4>' . $this->item->getName() . '</h4>';
foreach ($this->item->getProduct() as $product) {
echo $product->getSummary() . ' руб<br>';
}
echo '<p></p><span style="color: green">Итого:</span> ' . $this->item->getPrice() . '</p>';
echo '<hr>';
}
}
$product = new Product('Парта ученическая', 3999.99);
$product->action();
(new Show($product))->handler();
$collection = (new Product('Набор Пенал Ручка Карандаш'))->addProduct(new Product('Пенал', 20.50))
->addProduct(new Product('Ручка', 8.43))
->addProduct(new Product('Карандаш', 4.77));
(new Show($collection))->handler();
$cart = new Product('Корзина товаров');
$cart->addProduct(new Product('Ластик', 10.99))
->addProduct(new Product('Тетрадь в клетку', 9.73))
->addProduct($collection)
->addProduct(new Product('Линейка', 18.50))
->addProduct(new Product('Тетрадь в линейку', 9.73))
->action();
(new Show($cart))->handler();
$cart->addProduct(new Product('Набор стикеров', 5.18))
->action();
$collection->action();
(new Show($collection))->handler();
(new Show($cart))->handler();
_____________
Стимулятор ~yoomoney - 41001303250491